java设计模式实例分享

    科技2024-08-02  63

    1 代理模式(Proxy)

         Proxy模式又叫做代理模式,是构造型的设计 模式之一,它可以为其他对象提供一种代理(Proxy)以 控制对这个对象的访问。所谓代理,是指具有与代理元(被代理的对象)具有 相同的接口的类,客户端必须通过代理与被代理的目标 类交互,而代理一般在交互的过程中(交互前后),进行某些特别的处理。

    //subject(抽象主题角色):真实主题与代理主题的共同接口。 public interface Books { public double price(Double money); } //RealSubject(真实主题角色):定义了代理角色所代表的真实对象 public class RealSetBooks implements Books { public double price(Double money) { System.out.println("出厂价格是:" + money); return money; } } //Proxy(代理主题角色): 含有对真实主题角色的引用,代理角色通常在将客户端调用传递给真是主题对象之前或者之后执行某些操作,而不是单纯返回真实的对象。 public class ProxySetBooks implements Books { private RealSetBooks realSetBooks; public ProxySetBooks() { realSetBooks = new RealSetBooks(); } public double price(Double money) { System.out.println("售前处理"); Double price = realSetBooks.price(money) * 0.8; System.out.println("打八折"); return price; } } public class AutoProxy implements InvocationHandler { private RealSetBooks realSetBooks; public void setRealSetBooks(RealSetBooks realSetBooks) { this.realSetBooks = realSetBooks; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; System.out.println("售前处理"); try { result = method.invoke(realSetBooks, args); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } System.out.println("打八折"); System.out.println("自动代理"+(Double) result * 0.8+"元"); return result; } } public class MainClass { public static void main(String[] args) { //手动代理 /*ProxySetBooks proxySetBooks = new ProxySetBooks(); System.out.println("代理售后价格+" + proxySetBooks.price(100.0));*/ //动态代理 RealSetBooks realSetBooks = new RealSetBooks(); AutoProxy autoProxy = new AutoProxy(); autoProxy.setRealSetBooks(realSetBooks); Books proxySubject = (Books) Proxy.newProxyInstance( RealSetBooks.class.getClassLoader(), realSetBooks.getClass() .getInterfaces(), autoProxy); proxySubject.price(100.0); } }

    2 观察者模式(Observer)

          Observer模式是行为模式之一,它的作用是当一个对象的状态发生变化时,能够自动通知其他关联对象,自动刷新对象状态。Observer模式提供给关联对象一种同步通信的手段,使某个对象与依赖它的其他对象之间保持状态同步。

    //被观察对象 public class Blog{ private String title; private String content; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } //被观察者 public class BlogByObserver extends Observable { public void blog(Blog blog) { this.setChanged();// 指示已經改變,否则无法确定是否改变 this.notifyObservers(blog);//通知观察者,并且传递被观察对象对象 } } //观察者 public class BlogOberver implements Observer { public void update(Observable o, Object arg) { Blog blog = (Blog) arg; System.out.println("博客已经改变"); System.out.println("主题:" + blog.getTitle() + ";内容:" + blog.getContent()); } } public class MainClass { public static void main(String[] args) { BlogByObserver blogByObserver = new BlogByObserver();//实例化被观察者 blogByObserver.addObserver(new BlogOberver());// 注册观察者 Blog blog = new Blog(); blog.setTitle("主题"); blog.setContent("内容"); blogByObserver.blog(blog);//注入观察对象 } }

    3 策略模式(Strategy)         Strategy模式也叫策略模式是行为模式之一,它对一系列的算法加以封装,为所有算法定义一个抽象的算法接口,并通过继承该抽象算法接口对所有的算法加以封装和实现,具体的算法选择交由客户端决定(策略)。Strategy模式主要用来平滑地处理算法的切换

    //策略(算法)抽象 public abstract class Strategy { public abstract double cost(double num); } //打八折策略:各种策略(算法)的具体实现。 public class Straege1 extends Strategy { @Override public double cost(double num) { return num*0.8; } } //满100减五十策略:各种策略(算法)的具体实现。 public class Strategy2 extends Strategy { @Override public double cost(double num) { if (num>=100) { return num-50; } return num; } } //策略封装:策略的外部封装类,或者说策略的容器类。根据不同策略执行不同的行为。策略由外部环境决定。 public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy;//决定哪种策略 } public double cost(double num) { return this.strategy.cost(num); } } public class MainClass { public static void main(String[] args) { Context context=new Context(new Straege1()); double num=context.cost(800); System.out.println(num); } }

    4  包装器模式(Decorator)   装饰( Decorator )模式又叫做包装模式。通过一种对客户端透明的方式来扩展对象的功能,是继承关系的一个替换方案。

    //抽象组件角色: 一个抽象接口,是被装饰类和装饰类的父接口。 public interface Car { public void show(); public void run(); } //当抽象类实现接口时可以不实现所有的方法 public abstract class CarDecorator implements Car { private Car car; public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } public CarDecorator(Car car) { this.car = car; } public abstract void show(); } //具体组件角色:为抽象组件的实现类。 public class FlyCarDecorator extends CarDecorator{ public FlyCarDecorator(Car car) { super(car); } public void show() { this.getCar().show(); this.fly(); } public void fly() { System.out.println("FlyCarDecorator"); } public void run() { } } //具体组件角色:为抽象组件的实现类。 public class RunCar implements Car { public void run() { System.out.println("RunCar"); } public void show() { this.run(); } } //具体组件角色:为抽象组件的实现类。 public class SwimCarDecorator extends CarDecorator { public SwimCarDecorator(Car car) { super(car); } public void show() { this.getCar().show(); this.swim(); } public void swim() { System.out.println("SwimCarDecorator"); } public void run() { } } public class MainClass { public static void main(String[] args) { Car car = new RunCar(); car.show(); System.out.println("---------"); Car swimcar = new SwimCarDecorator(car); swimcar.show(); System.out.println("---------"); Car flySwimCar = new FlyCarDecorator(swimcar); flySwimCar.show(); } }

     5 适配器模式(Adapter)    Adapter模式也叫适配器模式,是构造型模式之一,通过Adapter模式可以改变已有类(或外部类)的接口形式

    //外部组件 public class Animal { public void animal1() { System.out.println("dog"); } public void animal2() { System.out.println("cat"); } } //通过委让实现Adapter public class Adapter2 { Animal animal; public Adapter2(Animal animal) { this.animal = animal; } public void dog() { animal.animal1(); } } //通过继承实现Adapter public class Adapter1 extends Animal { public void dog() { this.animal1(); } } public class MainClass { public static void main(String[] args) { // 继承实现适配器获取狗-----类适配器模 Adapter1 adapter1 = new Adapter1(); adapter1.dog(); // 委让实现适配器获取狗----对象适配器模式 Adapter2 adapter = new Adapter2(new Animal()); adapter.dog(); } }

     6 单例模式(Singleton)      单例模式是一种对象创建型模式,使用单例模式,可以保证为一个类只生成唯一的实例对象。也就是说,在整个程序空间中,该类只存在一个实例对象。其实,GoF对单例模式的定义是:保证一个类、只有一个实例存在,同时提供能对该实例加以访问的全局访问方法。

    public class Person { //final 全局共享变量,值不会变,保持一份 ,第二次创建的覆盖第一次创建的,final变量需要提供初值,否则编译不通过 private static final Person person=new Person(); private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } //私有构造函数不能new创建实例 private Person() { } public static Person getPerson() { return person; } } public class Person2 { private static Person2 person; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } //私有构造函数不能new创建实例 private Person2() { } /*线程使用全局同步,避免多线程实例化两个对象 * 局部同步和全局同步根据情况可以选择其一 */ public static synchronized Person2 getPerson() { if (person == null) { synchronized (Person2.class) {// 局部同步 if (person == null) {// 双重检查 person = new Person2(); } } } return person; } } public class MainClass { public static void main(String[] args) { Person2 person1 = Person2.getPerson(); person1.setName("aa"); Person2 person2 = Person2.getPerson(); person2.setName("bb"); System.out.println(person2.getName()); System.out.println(person1.getName()); System.out.println(person1==person2); Person person3 = Person.getPerson(); Person person4 = Person.getPerson(); Person person5 = Person.getPerson(); person3.setName("cc"); person4.setName("dd"); person5.setName("ff"); System.out.println(person3.getName()); System.out.println(person4.getName()); System.out.println(person3==person4); } }

    7 工厂方法模式(Factory Method)      工厂方法模式同样属于类的创建型模式又被称为多态工厂模式 。工厂方法模式的意义是定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不再负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口,这样进一步抽象化的好处是使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品

    public interface Animal { public void eat(); } public class buffalo implements Animal { public void eat() { System.out.println("i am buffalo eat straw"); } } public class Cat implements Animal { public void eat() { System.out.println("i am cat eat fish"); } } public class Dog implements Animal { public void eat() { System.out.println("i am dog eat bone"); } } //动物工厂接口 public interface AnimalFactory { public Animal getanmAnimal(); } //cat工厂 public class CatFactory implements AnimalFactory { public Animal getanmAnimal() { return new Cat(); } } //dog工厂 public class DogFactory implements AnimalFactory { public Animal getanmAnimal() { return new Dog(); } } public class MainClass { public static void main(String[] args){ AnimalFactory catfactory=new CatFactory(); Animal cat=catfactory.getanmAnimal(); cat.eat(); AnimalFactory dogFactory=new DogFactory(); Animal dog=dogFactory.getanmAnimal(); dog.eat(); } }

    8 简单工厂模式(simple factory)       简单工厂模式属于类的创建型模式,又叫做静态工厂方法模式。通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。

    public interface animal { public void eat(); } public class Cat implements animal { public void eat() { System.out.println("i am cat eat fish"); } } public class Dog implements animal { public void eat() { System.out.println("i am dog eat bone"); } } //简单工厂模式 public class Simplefactory public static animal getAnimal(String type) throws InstantiationException, IllegalAccessException { if (type.equalsIgnoreCase("dog")) { return Dog.class.newInstance();// 通过传递任何参数判断创建新的实例 } else if (type.equalsIgnoreCase("cat")) { return Cat.class.newInstance(); } else { System.out.println("没有找到实例"); return null; } } } public class MainClass { public static void main(String[] args) throws InstantiationException, IllegalAccessException { animal cat = Simplefactory.getAnimal("Cat");// 通过工厂类产生新的实例 cat.eat(); animal dog = Simplefactory.getAnimal("Dog"); dog.eat(); } }

    9 模板方法(Template Method)     Template Method模式也叫模板方法模式,是 行为模式之一,它把具有特定步骤算法中的某些必要的处理委让给抽象方法,通过子类继承对抽象方法的不同实现改变整个算法的行为。

    /* 旅行具有统一的操作步骤或操作过程:先买票后上车 * 抽象类的父类 */ public abstract class Travel { public abstract void buyTicket();//买票 public abstract void onbus();//上车 public void templateMethod() {//模板方法 this.buyTicket();//掉用子类的方法 this.onbus(); } } public class HanZhouTravel extends Travel { public void buyTicket() { System.out.println("买去杭州的车票"); } public void onbus() { System.out.println("上去杭州的车"); } } public class HuNanTravel extends Travel { public void buyTicket() { System.out.println("买去湖南的车票"); } public void onbus() { System.out.println("上去湖南的车"); } } public class MainClass { public static void main(String[] args) { Travel hunanTravel = new HuNanTravel(); hunanTravel.templateMethod(); Travel hanzhouTravel = new HanZhouTravel(); hanzhouTravel.templateMethod(); } }

    10 抽象工厂模式(abstractfactory)

        抽象工厂模式是所有形态的工厂模式中最为抽象和最其一般性的。抽象工厂模式可以向客户端提供一个接口,使得客户端在不必指定产品的具体类型的情况下,能够创建多个产品族的产品对象。

    public interface Fruit { public void get();//采集 } public abstract class Banana implements Fruit{ public abstract void get();//采集 } public abstract class Orange implements Fruit { public abstract void get();//采集 } public class NorthBanana extends Banana { public void get() { System.out.println("采集北方香蕉"); } } public class NorthOrange extends Orange { @Override public void get() { System.out.println("北橘子"); } } public class SouthBanana extends Banana { public void get() { System.out.println("采集南方香蕉"); } } public interface FruitFactory { public Fruit getBanana(); public Fruit getorange(); } public class NorthFruitFactory implements FruitFactory { public Fruit getBanana() { return new NorthBanana(); } public Fruit getorange() { return new NorthOrange(); } } public class SouthFruitFactory implements FruitFactory { public Fruit getBanana() { return new SouthBanana(); } public Fruit getorange() { // TODO Auto-generated method stub return null; } } public class MainClass { public static void main(String[] args) { FruitFactory ff = new NorthFruitFactory(); Fruit banana = ff.getBanana(); banana.get(); Orange orange = new NorthOrange(); orange.get(); FruitFactory ff2 =new SouthFruitFactory(); Fruit banana2 = ff2.getBanana(); banana2.get(); } }

    11 做桥接模式(Bridge)

    Bridge模式又叫做桥接模式,是构造型的设计模式之一。Bridge模式基于类的最小设计原则,通过使用封装,聚合以及继承等行为来让不同的类承担不同的责任。它的主要特点是把抽象(abstraction)与行为实现(implementation)分离开来,从而可以保持各部分的独立性以及应对它们的功能扩展。

    /*Abstraction * 抽象类接口(接口或抽象类) 维护对行为实现(Implementor)的引用 */ public interface IPeople { public String nature(); } public class Happy implements IPeople { public String nature() { return "happy"; } } public class Sad implements IPeople { public String nature() { return "sad"; } } //行为实现类接口 (Abstraction接口定义了基于Implementor接口的更高层次的操作) public abstract class Loving { private IPeople iPeople; public IPeople getiPeople() { return iPeople; } public Loving(IPeople iPeople) { super(); this.iPeople = iPeople; } public abstract void mood(); } //Client Bridge模式的使用者 public class Alisa extends Loving { public Alisa(IPeople iPeople) { super(iPeople); } @Override public void mood() { System.out.println("alisa is "+this.getiPeople().nature()); } } //Client Bridge模式的使用者 public class Allen extends Loving { public Allen(IPeople iPeople) { super(iPeople); } @Override public void mood() { System.out.println("allen is "+this.getiPeople().nature()); } } public class MainClass { public static void main(String[] args) { IPeople sad = new Sad(); Allen allen = new Allen(sad); allen.mood(); IPeople happy = new Happy(); Alisa alisa = new Alisa(happy); alisa.mood(); } }

    12  建造者模式或者生成器模式(Builder)

    Builder模式也叫建造者模式或者生成器模式, 是由GoF提出的23种设计模式中的一种。Builder模式是一种对象创建型模式之一,用来隐藏复合对象的创建过程,它把复合对象的创建过程加以抽象,通过子类继承和重载的方式,动态地创建具有复合属性的对象。

    public class House { private String floor; private String wall; public String getFloor() { return floor; } public void setFloor(String floor) { this.floor = floor; } public String getWall() { return wall; } public void setWall(String wall) { this.wall = wall; } } /* * 工程队 */ public interface HouseBulider { public void buliderwall(); public void buliderfloor(); public House getHouse(); } //工程师 public class Housedirector { public Housedirector(HouseBulider bulider) { bulider.buliderfloor(); bulider.buliderwall(); } } /* 公寓工程队 * */ public class GongyuBulider implements HouseBulider { House house = new House(); public void buliderfloor() { house.setFloor("公寓 floor"); } public void buliderwall() { house.setWall("公寓wall"); } public House getHouse() { return house; } } /* *平方工程队 */ public class PingfanBulider implements HouseBulider { House house = new House(); public void buliderfloor() { house.setFloor("平房floor"); } public void buliderwall() { house.setWall("平房wall"); } public House getHouse() { return house; } } public class MainClass { public static void main(String[] args) { HouseBulider GYbulider = new GongyuBulider();//公寓工程队 HouseBulider PFbulider = new PingfanBulider();//平房工程队 new Housedirector(PFbulider);//平房工程师 隐藏复合对象的创建过程 new Housedirector(GYbulider);//公寓工程师 隐藏复合对象的创建过程 House house = PFbulider.getHouse(); House house2 = GYbulider.getHouse(); System.out.println(house.getFloor()); System.out.println(house.getWall()); System.out.println(house2.getFloor()); System.out.println(house2.getWall()); } }

    13 命令模式(Command)

    是行为设计模式的一种。Command模式通过被称为 Command的类封装了对目标对象的调用行为以及调用参数。

    //Receiver需要被调用的目标对象。 public class Peddle { public void sailApple() { System.out.println("卖苹果"); } public void sailBanana() { System.out.println("卖香蕉"); } public void sailOranges() { System.out.println("卖橘子"); } } //CommandCommand抽象类。 public abstract class Command { private Peddle peddle; public Peddle getPeddle() { return peddle; } public void setPeddle(Peddle peddle) { this.peddle = peddle; } public Command(Peddle peddle) { super(); this.peddle = peddle; } public abstract void sail(); } //CommandCommand抽象类 public abstract class Command { private Peddle peddle; public Peddle getPeddle() { return peddle; } public void setPeddle(Peddle peddle) { this.peddle = peddle; } public Command(Peddle peddle) { super(); this.peddle = peddle; } public abstract void sail(); } //ConcreteCommand Command的具体实现类。 public class AppleCommand extends Command { public AppleCommand(Peddle peddle) { super(peddle); } @Override public void sail() { this.getPeddle().sailApple(); } } //ConcreteCommand Command的具体实现类。 public class BananaCommand extends Command { public BananaCommand(Peddle peddle) { super(peddle); } @Override public void sail() { this.getPeddle().sailBanana(); } } public class MainClass { public static void main(String[] args) { Peddle peddle=new Peddle(); Command appleCommand=new AppleCommand(peddle); Command bananaCommand=new BananaCommand(peddle); Waiter waiter=new Waiter(); waiter.order(appleCommand); waiter.order(bananaCommand); // waiter.remove(appleCommand); waiter.sail(); } }

    14 组合模式(Composite)

    Composite模式也叫组合模式,是构造型的设计模式之一。通过递归手段来构造树形的对象结构,并可以通过一个对象来访问整个对象树。

    public interface Ifile { public void display(); public boolean add(Ifile file); public boolean delete(Ifile file); public List<Ifile> getChild(); public List<Ifile> getChild2(); } public class File implements Ifile { private String name; public File(String name) { this.name = name; } public boolean add(Ifile file) { return false; } public boolean delete(Ifile file) { return false; } public void display() { System.out.println("file:"+name); } public List<Ifile> getChild() { return null; } public List<Ifile> getChild2() { return null; } } public class Folder implements Ifile { private String name; private int num; private List<Ifile> children; private List<Ifile> children2; public Folder(String name) { this.name = name; children = new ArrayList<Ifile>(); } public Folder(String name, int num) { this.name = name; this.num = num; children2 = new ArrayList<Ifile>(); } public boolean add(Ifile file) { return children.add(file); } public boolean add2(Ifile file) { return children2.add(file); } public boolean delete(Ifile file) { return children.remove(file); } public void display() { System.out.println(name); } public List<Ifile> getChild() { return children; } public List<Ifile> getChild2() { return children2; } } public class MainClass { public static void main(String[] args) { // test1(); test2(); } /* * 实验一 */ public static void test1() { // C盘 Folder rootFolder = new Folder("C:"); // allen目录 Folder allen = new Folder("allen");// 文件夹 File beifengFile = new File("allen.txt");// 文件 File beifengFile2 = new File("allen2.txt"); rootFolder.add(allen); rootFolder.add(beifengFile); rootFolder.add(beifengFile2); // alisa目录 Folder alisa = new Folder("alisa");// 文件夹 File ibeifengFile = new File("alisa1.txt"); File ibeifengFile2 = new File("alisa2.txt"); rootFolder.add(alisa); rootFolder.add(ibeifengFile); rootFolder.add(ibeifengFile2); displayTree(rootFolder, 0); } public static void displayTree(Ifile rootFolder, int deep) { for (int i = 0; i < deep; i++) { System.out.print("----"); } rootFolder.display();// 显示自身的名称 List<Ifile> children = rootFolder.getChild();// 获得子树 // 遍历子树 for (Ifile file : children) { if (file instanceof File) { for (int i = 0; i <= deep; i++) { System.out.print("--"); } file.display(); } else { displayTree(file, deep + 1); } } } /* * 实验二 */ public static void test2() { Folder folder = new Folder("D:"); Folder folder2 = new Folder("allen", 0); File file = new File("zjm"); File file2 = new File("every"); folder2.add2(file); folder2.add2(file2); folder.add(folder2); Folder folder3 = new Folder("alisa", 0); File file3 = new File("xyf"); File file4 = new File("fxy"); folder3.add2(file3); folder3.add2(file4); folder.add(folder3); List<Ifile> folders = folder.getChild(); folder.display(); for (Ifile ifile2 : folders) { System.out.print("---"); ifile2.display(); List<Ifile> ifiles = ifile2.getChild2(); for (Ifile ifile : ifiles) { ifile.display(); } } } }

    15 职责链模式(Chain of Responsibility(CoR))

     Chain of Responsibility(CoR)模式也叫职责链模式或者职责连锁模式,是行为模式之一,该模式构造一系列分别担当不同的职责的类的对象来共同完成一个任务,这些类的对象之间像链条一样紧密相连,所以被称作职责链模式。

    //Handler 处理类的抽象父类。 public abstract class Graduate { public abstract void Do(); protected Graduate graduate;//子类可以访问 ,用private修饰符子类不能访问 public Graduate getGraduate() { return graduate; } public Graduate setGraduate(Graduate graduate) { this.graduate = graduate; return this.graduate; } } //concreteHandler具体的处理类。 public class DaBian extends Graduate { @Override public void Do() { System.out.println("答辩"); if (this.getGraduate()!=null) { this.getGraduate().Do(); } } } //concreteHandler具体的处理类。 public class ReadSys extends Graduate { @Override public void Do() { System.out.println("阅读系统"); if (this.getGraduate()!=null) { this.getGraduate().Do(); } } } //concreteHandler具体的处理类。 public class ReadSys extends Graduate { @Override public void Do() { System.out.println("阅读系统"); if (this.getGraduate()!=null) { this.getGraduate().Do(); } } } public class MainClass { //系统阅读-》论文阅读-》答辩 public static void main(String[] args) { Graduate readsys = new ReadSys(); Graduate readtopic = new ReadTopic(); Graduate dabian = new DaBian(); readsys.setGraduate(readtopic).setGraduate(dabian); readsys.Do(); } }

    16 外观模式(Facade)   Facade模式也叫外观模式,是由GoF提出的 23种设计模式中的一种。Facade模式为一组具 有类似功能的类群,比如类库,子  系统等等,提供一个一致的简单的界面。这个一致的简单的界 面被称作facade。

    public class Cat { public void buy() { System.out.println("Buy Cat"); } } public class Dog { public void buy() { System.out.println("buy dog"); } } // 功能提供者。指提供功能的类群(模块或子系统) public class FacadeAnimal { private Cat cat; private Dog dog; public FacadeAnimal() { cat = new Cat(); dog = new Dog(); } public void buy() { this.cat.buy(); this.dog.buy(); //this.buy(); } } public class MainClass { public static void main(String[] args) { FacadeAnimal facadeAnimal = new FacadeAnimal(); facadeAnimal.buy();//通过外观模式功能提供者同时buy cat 和 buy dog } }

    17 享元模式(Flyweigh)

    Flyweight模式也叫享元模式,是构造型模式之一,它通过与其他类似对象共享数据来减小内存占用。

    public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(String name, int age) { super(); this.name = name; this.age = age; } public Person() { } } public class Teacher extends Person { private String number; public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public Teacher(String name, int age, String number) { super(name, age);//继承 this.number = number; } public Teacher() { super();//继承 } } public class TeacherFactory { private Map<String, Teacher> teachers; public TeacherFactory() { teachers=new HashMap<String, Teacher>(); } public Teacher getTeacher(String number) { Teacher teacher = teachers.get(number); if(teacher == null) { System.out.println("coming"); teacher = new Teacher(); teacher.setNumber(number); teachers.put(number, teacher); } return teacher; } } public class MainClass { public static void main(String[] args) { TeacherFactory factory = new TeacherFactory(); Teacher teacher1 = factory.getTeacher("0102034"); Teacher teacher2 = factory.getTeacher("0102035"); Teacher teacher3 = factory.getTeacher("0102034"); Teacher teacher4 = factory.getTeacher("0102037"); System.out.println(teacher1.getNumber()); System.out.println(teacher2.getNumber()); System.out.println(teacher3.getNumber()); System.out.println(teacher4.getNumber()); if (teacher1 == teacher3) { System.out.println("true"); } else { System.out.println("false"); } } }

    18 解释器模式(interpreter)

    interpreter模式也叫解释器模式,是行为模式之一,它是一种特殊的设计模式,它建立一个解释器,对于特定的计算机程序设计语言,用来解释预先定义的文法。简单地说,Interpreter模式是一种简单的语法解释器构架。

    //抽象解释器 public abstract class Express { public abstract void Interpreter(); } //递增解释器 public class PlusExpress extends Express { private Context context; public PlusExpress(Context context) { super(); this.context = context; } @Override public void Interpreter() { System.out.println("递增"); String stringinput=this.context.getInput(); int intinput= Integer.parseInt(stringinput);//字符类型转换为整数类型 intinput++; this.context.setOutput(String.valueOf(intinput));//整数类型转换为字符类型 } } //减法解释器 public class SubExpress extends Express { private Context context; public SubExpress(Context context) { super(); this.context = context; } @Override public void Interpreter() { System.out.println("递减"); String stringinput = context.getInput(); int intinput = Integer.parseInt(stringinput);// 字符类型转换为整数类型 int sub = 3; int num = intinput - sub; this.context.setOutput(String.valueOf(num));// 整数类型转换为字符类型 } } //上下文 public class Context { private String input; private String output; public String getInput() { return input; } public void setInput(String input) { this.input = input; } public String getOutput() { return output; } public void setOutput(String output) { this.output = output; } public Context(String input) { super(); this.input = input; } } public class MainClass { public static void main(String[] args) { String num = "20"; Context context = new Context(num); List<Express> expresses = new ArrayList<Express>(); PlusExpress plusExpress = new PlusExpress(context); SubExpress subExpress = new SubExpress(context); expresses.add(plusExpress); expresses.add(subExpress); for (Express express : expresses) { express.Interpreter(); System.out.println(context.getOutput()); } } }

    19 迭代模式(Iterator)

      Iterator模式也叫迭代模式,是行为模式之 一,它把对容器中包含的内部对象的访问委让给外部类,使用Iterator(遍历)按顺序进行遍历访问的设计模式。

    public class Book { private Integer num; private String nmae; public Book(Integer num, String nmae) { super(); this.num = num; this.nmae = nmae; } public Integer getNum() { return num; } public String getNmae() { return nmae; } public void show() { System.out.println(nmae+num); } } //1.由容器自己实现顺序遍历。直接在容器类里直接添加顺序遍历方法 public class BookList { List<Book> books; int index = 0; public BookList() { books = new ArrayList<Book>(); } public void addzbook(Book book) { books.add(book); } public void removebook(Book book) { Integer inbook = books.indexOf(book); books.remove(inbook); } public boolean hasnext() { if (index >= books.size()) { System.out.println("end"); return false; } else { return true; } } public Book getNext() { return books.get(index++); } } public class MainClass { public static void main(String[] args) { BookList bookList = new BookList(); Book book1 = new Book(88, "allen"); Book book2 = new Book(99, "Alisa"); bookList.addzbook(book1); bookList.addzbook(book2); while (bookList.hasnext()) { Book book = bookList.getNext(); book.show(); } } }

    20 中介者模式(Mediator)

    Mediator模式也叫中介者模式,是由GoF提出的23种软件设计模式的一种。Mediator模式是行为模式之一,在Mediator模式中,类之间的交互行为被统一放在Mediator的对象中,对象通过Mediator对象同其他对象 交互,Mediator对象起着控制器的作用。

    // colleague关联类的抽象父类。 public abstract class Person { private String name; private int condition; private Imediator imediator; public Imediator getImediator() { return imediator; } public void setImediator(Imediator imediator) { this.imediator = imediator; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCondition() { return condition; } public void setCondition(int condition) { this.condition = condition; } public Person(String name, int condition, Imediator imediator) { this.name = name; this.condition = condition; this.imediator = imediator; } public abstract void getcompanion(Person person); } //mediator中介者类的抽象父类。 public abstract class Imediator { private Man man; private Woman woman; public Man getMan() { return man; } public void setMan(Man man) { this.man = man; } public Woman getWoman() { return woman; } public void setWoman(Woman woman) { this.woman = woman; } public abstract void getMiss(Person person); } //concreteColleague具体的关联类。 public class Woman extends Person { public Woman(String name, int condition, Imediator imediator) { super(name, condition, imediator); } @Override public void getcompanion(Person person) { this.getImediator().setWoman(this); this.getImediator().getMiss(person); } } //concreteColleague具体的关联类。 public class Man extends Person { public Man(String name, int condition, Imediator imediator) { super(name, condition, imediator); } @Override public void getcompanion(Person person) { this.getImediator().setMan(this);//加入man本事 this.getImediator().getMiss(person);//寻找woman对象 } } public class MainClass { public static void main(String[] args) { Imediator imediator = new Mediator(); Person allen = new Man("zjm", 20, imediator); Person alisa = new Woman("fxy", 20, imediator); allen.getcompanion(alisa); } }

    21 备忘录模式(Memento)

    所谓的备忘录,顾名思义,可以用来备份的东西,比如游戏的存档,数据库的快照等等, 就是对某一项内容进行数据备份,在必要时可以通过这个备份进行数据的恢复或者回退,将数据恢复或者回退到备份前的状态。

    //Originator(原生者) public class People { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Memento createMemento() { return new Memento(this.name, this.age); } public void getMemento(Memento memento) { this.name = memento.getName(); this.age = memento.getAge(); } public People(String name, int age) { super(); this.name = name; this.age = age; } } //备忘录 public class Memento { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Memento(String name, int age) { super(); this.name = name; this.age = age; } } //备忘录Caretaker(管理者) public class Caretaker { private Memento memento; public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento = memento; } } public class MainClass { public static void main(String[] args) { People people = new People("allen", 24); Caretaker caretaker = new Caretaker(); caretaker.setMemento(people.createMemento()); people.setName("alisa"); people.setAge(23); people.getMemento(caretaker.getMemento()); System.out.println("name=" + people.getName() + ",age=" + people.getAge()); } }

    22 原型模式(Prototype)

    Prototype模式是一种对象创建型模式,它采取复制原型对象的方法来创建对象的实例。使用Prototype模式创建的实例,具有与原型一样的数据

    public class Person implements Cloneable { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person clone() { try { return (Person) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } } public class MainClass { public static void main(String[] args) { Person person = new Person(); person.setName("allen"); person.setAge(24); Person person2 = person.clone();//第二次克隆第一次的 person2.setAge(25); System.out.println(person.getName()+""+person.getAge()); System.out.println(person2.getName()+""+person2.getAge());//第二次创建的,如果值没有手动改变,则结果为第一次创建的 System.out.println(person == person2);//原型模式每次创建的不一样,返回false }

    23 单一职责原则(Single Responsibility Principle )

    单一职责原则(Single Responsibility Principle ):就一个类而言,应该仅有一个引起它变化的原因

    public class Input { private String username; private String upassword; //获得客户端输入 public void shuru() { Scanner scanner = new Scanner(System.in); System.out.println("请输入用户名"); username = scanner.nextLine(); System.out.println("请输入密码"); upassword = scanner.nextLine(); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUpassword() { return upassword; } public void setUpassword(String upassword) { this.upassword = upassword; } } public class DAOImp { //进行数据操作 public void save(String username, String upassword) { //System.out.println("将" + username + "保存到了数据库"); //System.out.println("将" + upassword + "保存到了数据库"); } } public class DBManager { //连接数据库 public static void getConnection() { System.out.println("获得数据库连接"); } } public class Validator { //进行数据校验 public boolean validate(String username, String upassword) { if(username == null || "".equals(username.trim())) { System.out.println("用户名不能为空"); return false; } if(upassword == null || "".equals(upassword.trim())) { System.out.println("密码不能为空"); return false; } return true; } } public class MainClass { public static void main(String[] args) { Input input = new Input(); input.shuru(); Validator validator = new Validator(); if (validator.validate(input.getUsername(), input.getUpassword())) { DBManager.getConnection(); DAOImp dao = new DAOImp(); dao.save(input.getUsername(), input.getUpassword()); } } }

    24 状态模式(State)

    State模式也叫状态模式,是行为设计模式的一种。State模式允许通过改变对象的内部状态而改变对象的行为,这个对象表现得就好像修改了它的类一样。

    /* * Context:用户对象 拥有一个State类型的成员,以标识对象的当前 状态; */ public class Person { private Integer hour; private Istate istate; public Person() { super(); this.istate = new MorinState(); } public Integer getHour() { return hour; } public void setHour(Integer hour) { this.hour = hour; } public void Idosthing() { istate.doSthing(this); // 复位,都所以方法以后再执行。 istate = new MorinState(); } public Istate getIstate() { return istate; } public void setIstate(Istate istate) { this.istate = istate; } } /* * State:接口或基类 封装与Context的特定状态相关的行为; */ public abstract class Istate { public abstract void doSthing(Person person); } /* *ConcreteState:接口实现类或子类 实现了一个与Context某个状态相关的行为。 */ public class NoonState extends Istate { @Override public void doSthing(Person person) { if (person.getHour()==12) { System.out.println("午餐"); }else { person.setIstate(new Nostate()); person.Idosthing(); } } } public class Nostate extends Istate { @Override public void doSthing(Person person) { System.out.println(person.getHour()+"未定义"); } } /* * ConcreteState:接口实现类或子类 实现了一个与Context某个状态相关的行为。 */ public class MorinState extends Istate { @Override public void doSthing(Person person) { if (person.getHour() == 7) { System.out.println("早餐"); } else { person.setIstate(new NoonState()); person.Idosthing(); } } } public class MainClass { public static void main(String[] args) { Person person = new Person(); person.setHour(7); person.Idosthing(); person.setHour(12); person.Idosthing(); person.setHour(9); person.Idosthing(); person.setHour(7); person.Idosthing(); } }

    25 访问者模式(Visitor)

    Visitor模式也叫访问者模式,是行为模式之一,它分离对象的数据和行为,使用Visitor模式,可以不修改已有类的情况下,增加新的操作。

    //公园每一部分的抽象 public interface ParkElement { //用来接纳访问者 public void accept(Visitor visitor); } //公园的A部分 public class ParkA implements ParkElement { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void accept(Visitor visitor) { visitor.visit(this); } } //公园的B部分 public class ParkB implements ParkElement{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void accept(Visitor visitor) { visitor.visit(this); } } public class Park implements ParkElement { private String name; private ParkA parkA; private ParkB parkB; public Park() { this.parkA = new ParkA(); this.parkB = new ParkB(); parkA.setName("A"); parkB.setName("B"); } public void accept(Visitor visitor) { visitor.visit(this); parkA.accept(visitor); parkB.accept(visitor); } public String getName() { return name; } public void setName(String name) { this.name = name; } } //清洁工 public interface Visitor { public void visit(Park park); public void visit(ParkA parkA); public void visit(ParkB parkB); } //清洁工A,负责parkA的卫生情况 public class VisitorA implements Visitor { public void visit(Park park) { } public void visit(ParkA parkA) { System.out.println("清洁工A:完成公园" + parkA.getName()+ "的卫生"); } public void visit(ParkB parkB) { } } //清洁工B,负责公园B部分的卫生 public class VisitorB implements Visitor { public void visit(Park park) { } public void visit(ParkA parkA) { } public void visit(ParkB parkB) { System.out.println("清洁工B:完成公园" + parkB.getName()+"的卫生"); } } public class VisitorManager implements Visitor { public void visit(Park park) { System.out.println("管理员:负责" + park.getName() + "卫生检查"); } public void visit(ParkA parkA) { System.out.println("管理员:负责公园"+ parkA.getName() +"部分卫生检查"); } public void visit(ParkB parkB) { System.out.println("管理员:负责公园"+ parkB.getName() +"分部卫生检查"); } } public class MainClass { public static void main(String[] args) { Park park = new Park(); park.setName("越秀公园"); VisitorA visitorA = new VisitorA(); park.accept(visitorA); VisitorB visitorB = new VisitorB(); park.accept(visitorB); VisitorManager visitorManager = new VisitorManager(); park.accept(visitorManager); } }

     

    Processed: 0.022, SQL: 8