设计模式需要遵循的原则:
一、单一职责原则
1、接口一定要做到单一原则
2、类的设计尽量做到单一原则
接口的单一原则代码示例:
二、里氏替换原则
1、只要父类出现的地方,子类就可以出现,而且替换为子类不会有任何问题;相反的话,就不行了。
2、子类必须完全实现父类的方法
3、子类可以有自己的个性
4、覆盖或实现父类的方法时输入参数可以被放大(这里是指输入参数子类可以比父类的输入参数范围大),也就是重载,(否则的话会出现子类没有重写父类的方法但是子类的方法也可以被执行的情况,这样子的情况是很不合理的)
5、覆写或实现父类的方法时,输出结果可以被缩小,也就是重写
三、依赖倒置原则
1、模块间的依赖通过抽象发生,实现类之间不发生直接的依赖关系,其依赖关系是通过接口或抽象类产生的。
2、接口或抽象类不依赖于实现类
3、实现类依赖接口或者抽象类
总之,接口负责定义public属性和方法,并且声明与其他对象的依赖关系;抽象类负责公共构造部分的实现;实现类精确的实现业务逻辑,同时在适当的时候对父类进行细化。
具体应用:只要把抽象层定义好,就可以真正的并行的开发了
依赖注入方式:
1、接口的依赖注入
2、构造方法依赖注入
3、setter方法依赖注入
四、接口隔离原则
1、接口设计的粒度要细,要遵循单一职责原则,不能很多功能强耦合在一个接口里;但也要适当的细分,不能无限制的细分下去。
根据接口隔离原则拆分接口时,首先必须满足单一职责原则。
五、迪米特法则
1、迪米特法则要求类“羞涩”一点,尽量不要对外公布太多的public方法和非静态的public变量,尽量内敛,多使用private、default、protected、final。
朋友类的定义:
具体原则:
1、只和朋友交流
2、朋友之间也是有距离的,不能太亲密
3、是自己的就是自己的(最好不要增加类间的关系)
4、谨慎使用Serializable
六、开闭原则(最重要的原则)对扩展开放,对修改关闭
1、通过接口或抽象类约束扩展,对扩展进行边界限定,不允许出现在接口或抽象类中不存在的public方法
2、参数类型、引用对象尽量使用接口或者抽象类,而不是实现类
3、抽象层尽量保持稳定,一旦确定及不允许修改
4、用类的扩展和重写来代替类的修改
5、元数据控制模块行为(spring控制反转,配置文件)
设计模式:
1、单例模式(扩展:固定数量多例模式)
public class SinglePattern { private SinglePattern() { } private static final SinglePattern instance = new SinglePattern(); public static SinglePattern getInstance() { return instance; }}class SinglePattern2{ private SinglePattern2() { } private static SinglePattern2 instance = null; public static SinglePattern2 getInstance() { if(instance==null) { synchronized (SinglePattern2.class) { if(instance==null) { instance = new SinglePattern2(); } } } return instance; }}class SinglePattern3{ //这种实现方式性能比较差 private SinglePattern3() { } private static SinglePattern3 instance = null; public static synchronized SinglePattern3 getInstance() { if(instance==null) { instance = new SinglePattern3(); } return instance; }}
2、工厂方法模式
public class Creator extends AbstractCreator{ @Override publicT createProduct(Class clazz) { // TODO Auto-generated method stub try { return (T)Class.forName(clazz.getName()).newInstance(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { Creator creator = new Creator(); AbstarctProducer producer = creator.createProduct(Producer1.class); producer.method2(); } }abstract class AbstractCreator { public abstract T createProduct(Class clazz);}abstract class AbstarctProducer{ public void method1(){ } public abstract void method2();}class Producer1 extends AbstarctProducer{ @Override public void method2() { // TODO Auto-generated method stub System.out.println("AA"); }}
静态工厂模式
public class Creator{ public staticT createProduct(Class clazz) { // TODO Auto-generated method stub try { return (T)Class.forName(clazz.getName()).newInstance(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { AbstarctProducer producer = Creator.createProduct(Producer1.class); producer.method2(); } }//abstract class AbstractCreator {//// public abstract T createProduct(Class clazz);//}abstract class AbstarctProducer{ public void method1(){ } public abstract void method2();}class Producer1 extends AbstarctProducer{ @Override public void method2() { // TODO Auto-generated method stub System.out.println("AA"); }}
多工厂模式
public class CreatorProducer1 extends AbstractCreator{ @Override public AbstarctProducer createProduct() { // TODO Auto-generated method stub return new Producer1(); } }class CreatorProducer2 extends AbstractCreator{ @Override public AbstarctProducer createProduct() { // TODO Auto-generated method stub return new Producer2(); } }abstract class AbstractCreator { public abstract AbstarctProducer createProduct();}abstract class AbstarctProducer{ public void method1(){ } public abstract void method2();}class Producer1 extends AbstarctProducer{ @Override public void method2() { // TODO Auto-generated method stub System.out.println("AA"); }}class Producer2 extends AbstarctProducer{ @Override public void method2() { // TODO Auto-generated method stub System.out.println("BB"); }}
负责产生单例的工厂类
延迟加载的工厂类
3、抽象工厂模式
public class MaleFactory implements HumanFactory{ public MaleFactory() { // TODO Auto-generated constructor stub } @Override public Human createYellowHuman() { // TODO Auto-generated method stub return new MaleYellowHuman(); } @Override public Human createBlackHuman() { // TODO Auto-generated method stub return new MaleBlackHuman(); } @Override public Human createWhiteHuman() { // TODO Auto-generated method stub return new MaleWhiteHuman(); }}interface HumanFactory{ public Human createYellowHuman(); public Human createBlackHuman(); public Human createWhiteHuman(); }class FemaleFactory implements HumanFactory{ @Override public Human createYellowHuman() { // TODO Auto-generated method stub return new FemaleYellowHuman(); } @Override public Human createBlackHuman() { // TODO Auto-generated method stub return new FemaleBlackHuman(); } @Override public Human createWhiteHuman() { // TODO Auto-generated method stub return new FemaleWhiteHuman(); } }interface Human{ public void getColor(); public void talk(); public void getSex();}abstract class AbstractWhiteHuman implements Human{ public void getColor() { // TODO Auto-generated method stub System.out.println("White"); } public void talk() { // TODO Auto-generated method stub System.out.println("English"); }}abstract class AbstractYellowHuman implements Human{ public void getColor() { // TODO Auto-generated method stub System.out.println("Yellow"); } public void talk() { // TODO Auto-generated method stub System.out.println("Chinese"); }}abstract class AbstractBlackHuman implements Human{ public void getColor() { // TODO Auto-generated method stub System.out.println("Black"); } public void talk() { // TODO Auto-generated method stub System.out.println("BlackYu"); }}class FemaleYellowHuman extends AbstractYellowHuman{ @Override public void getSex() { // TODO Auto-generated method stub System.out.println("Female"); } }class MaleYellowHuman extends AbstractYellowHuman{ @Override public void getSex() { // TODO Auto-generated method stub System.out.println("male"); } }class FemaleBlackHuman extends AbstractBlackHuman{ @Override public void getSex() { // TODO Auto-generated method stub System.out.println("Female"); } }class MaleBlackHuman extends AbstractBlackHuman{ @Override public void getSex() { // TODO Auto-generated method stub System.out.println("male"); } }class FemaleWhiteHuman extends AbstractWhiteHuman{ @Override public void getSex() { // TODO Auto-generated method stub System.out.println("Female"); } }class MaleWhiteHuman extends AbstractWhiteHuman{ @Override public void getSex() { // TODO Auto-generated method stub System.out.println("male"); } }
4、模板方法模式
public class CreateBWM extends AbstractCreateBWM{ @Override protected void start() { // TODO Auto-generated method stub System.out.println("START"); } @Override protected void stop() { // TODO Auto-generated method stub System.out.println("STOP"); } @Override protected void alarm() { // TODO Auto-generated method stub System.out.println("ALARM"); } public static void main(String[] args) { CreateBWM bwm = new CreateBWM(); bwm.run(); }}abstract class AbstractCreateBWM{ protected abstract void start(); protected abstract void stop(); protected abstract void alarm(); public final void run() { this.start(); this.alarm(); this.stop(); }}
5、建造者模式(生成器模式)(可以自己定义模板的模板模式)
import java.util.ArrayList;public class CreateBWM extends AbstractCreateCar{ @Override protected void start() { // TODO Auto-generated method stub System.out.println("BWMSTART"); } @Override protected void stop() { // TODO Auto-generated method stub System.out.println("BWMSTOP"); } @Override protected void alarm() { // TODO Auto-generated method stub System.out.println("BWMALARM"); } public static void main(String[] args) { CreateBWM bwm = new CreateBWM(); bwm.run(); }}class CreateBenz extends AbstractCreateCar{ @Override protected void start() { // TODO Auto-generated method stub System.out.println("BenzSTART"); } @Override protected void stop() { // TODO Auto-generated method stub System.out.println("BenzSTOP"); } @Override protected void alarm() { // TODO Auto-generated method stub System.out.println("Benzalarm"); } }abstract class AbstractCreateCar{ private ArrayListsequence = new ArrayList<>(); protected abstract void start(); protected abstract void stop(); protected abstract void alarm(); public final void run() { for(int i=0;i sequence){ this.sequence = sequence; }}abstract class CarBuilder{ public abstract void setSequence(ArrayList sequence); public abstract AbstractCreateCar getCarModel();}class BWMBuilder extends CarBuilder{ private CreateBWM bwm = new CreateBWM(); @Override public void setSequence(ArrayList sequence) { // TODO Auto-generated method stub this.bwm.setSequence(sequence); } @Override public AbstractCreateCar getCarModel() { // TODO Auto-generated method stub return this.bwm; } }class BenzBuilder extends CarBuilder{ private CreateBenz benz = new CreateBenz(); @Override public void setSequence(ArrayList sequence) { // TODO Auto-generated method stub this.benz.setSequence(sequence); } @Override public AbstractCreateCar getCarModel() { // TODO Auto-generated method stub return this.benz; } }class Director{ private ArrayList sequence = new ArrayList<>(); private BenzBuilder benz = new BenzBuilder(); private BWMBuilder bwm = new BWMBuilder(); public CreateBenz getBenz() { this.sequence.clear(); this.sequence.add("start"); this.sequence.add("stop"); this.benz.setSequence(this.sequence); return (CreateBenz)this.benz.getCarModel(); } public CreateBWM getBWM() { this.sequence.clear(); this.sequence.add("start"); this.sequence.add("alarm"); this.benz.setSequence(this.sequence); return (CreateBWM)this.benz.getCarModel(); }}
6、代理模式(委托模式)(也可以在代理类的接口中增加before与after接口)
public class Proxy implements IGamePlayer{ public Proxy(IGamePlayer player) { // TODO Auto-generated constructor stub this.player = player; } private IGamePlayer player = null; @Override public void login(String user, String password) { // TODO Auto-generated method stub this.player.login(user, password); } @Override public void killBoss() { // TODO Auto-generated method stub this.player.killBoss(); } @Override public void upgrade() { // TODO Auto-generated method stub this.player.upgrade(); } public static void main(String[] args) { IGamePlayer player = new GamePlayer("yy"); IGamePlayer proxy = new Proxy(player); proxy.login("aa", "bb"); proxy.killBoss(); proxy.upgrade(); }}interface IGamePlayer{ public void login(String user, String password); public void killBoss(); public void upgrade();}class GamePlayer implements IGamePlayer{ private String name = ""; public GamePlayer(String name) { // TODO Auto-generated constructor stub this.name = name; } @Override public void login(String user, String password) { // TODO Auto-generated method stub System.out.println("登录"); } @Override public void killBoss() { // TODO Auto-generated method stub System.out.println("打怪"); } @Override public void upgrade() { // TODO Auto-generated method stub System.out.println("升级"); } }
7、原型模式clone
8、中介者模式
import java.util.Random;public class Mediaer extends AbstarctMediaer{ public Mediaer() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub AbstarctMediaer mediaer = new Mediaer(); Purchase purchase = new Purchase(mediaer); purchase.buyIBMcomputer(100); Sale sale = new Sale(mediaer); sale.sellIBMComputer(1); Stock stock = new Stock(mediaer); stock.clearStock(); } @Override public void execute(String str, Object... objects) { // TODO Auto-generated method stub if(str.equals("purchase.buy")) { this.buyComputer((Integer)objects[0]); }else if(str.equals("sale.sell")) { this.sellComputer((Integer)objects[0]); }else if(str.equals("sale.offsell")) { this.offSell(); }else if(str.equals("stock.clear")){ this.clearStock(); } } private void buyComputer(int number) { int saleStatus = super.sale.getSaleStatus(); if(saleStatus>80) { System.out.println("采购IBM电脑"+number+"台"); super.stock.increase(number); }else { int buyNumber = number/2; System.out.println("采购IBM电脑"+buyNumber+"台"); } } private void sellComputer(int number) { if(super.stock.getStockNumber()
9、命令模式(项目接口人模式)(接收者要对外隐藏起来,封装好)
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub Invoker invoker = new Invoker(); Command cmd1 = new ConcreteCommand1(); invoker.setCmd(cmd1); invoker.action(); Command cmd2 = new ConcreteCommand2(); invoker.setCmd(cmd2); invoker.action(); }}//执行命令者class Invoker{ private Command cmd; public void setCmd(Command cmd) { this.cmd = cmd; } public void action() { this.cmd.executeCommand(); }}//命令abstract class Command{ protected ConcreteReceiver1 r1 = new ConcreteReceiver1(); protected ConcreteReceiver2 r2 = new ConcreteReceiver2(); public abstract void executeCommand(); }class ConcreteCommand1 extends Command{ @Override public void executeCommand() { // TODO Auto-generated method stub super.r1.doSomething(); super.r2.doSomething(); } }class ConcreteCommand2 extends Command{ @Override public void executeCommand() { // TODO Auto-generated method stub super.r1.doAnything(); super.r2.doAnything(); } }//接收命令者abstract class AbstractReceiver{ public abstract void doSomething(); public abstract void doAnything();}class ConcreteReceiver1 extends AbstractReceiver{ @Override public void doSomething() { // TODO Auto-generated method stub System.out.println("ConcreteReceiver1+doSomething"); } @Override public void doAnything() { // TODO Auto-generated method stub System.out.println("ConcreteReceiver1+doAnything"); } }class ConcreteReceiver2 extends AbstractReceiver{ @Override public void doSomething() { // TODO Auto-generated method stub System.out.println("ConcreteReceiver2+doSomething"); } @Override public void doAnything() { // TODO Auto-generated method stub System.out.println("ConcreteReceiver2+doAnything"); } }
10、责任链模式
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub Handler h1 = new ConcreteHandler1(); Handler h2 = new ConcreteHandler2(); h1.setNextHandler(h2); Request request = new Request(Level.A); h1.handleMessage(request); Request request2 = new Request(Level.B); h2.handleMessage(request2); }}abstract class Handler{ private Handler nextHandler; public void setNextHandler(Handler nextHandler) { this.nextHandler = nextHandler; } protected abstract Response echo(Request request); protected abstract Level getHandlerLevel(); public final Response handleMessage(Request request) { Response response = null; if(this.getHandlerLevel()==request.getRequestLevel()) { response = this.echo(request); }else { if(this.nextHandler!=null) { this.nextHandler.handleMessage(request); }else { } } return response; }}class ConcreteHandler1 extends Handler{ @Override protected Response echo(Request request) { // TODO Auto-generated method stub return new Response("ConcreteHandler1"); } @Override protected Level getHandlerLevel() { // TODO Auto-generated method stub return Level.A; } }class ConcreteHandler2 extends Handler{ @Override protected Response echo(Request request) { // TODO Auto-generated method stub return new Response("ConcreteHandler2"); } @Override protected Level getHandlerLevel() { // TODO Auto-generated method stub return Level.B; } }enum Level{ A,B;}class Request{ private Level level; public Request(Level level) { // TODO Auto-generated constructor stub this.level = level; } public Level getRequestLevel() { return this.level; }}class Response{ public Response(String message) { // TODO Auto-generated constructor stub System.out.println(message); }}
11、装饰模式(一种特殊的代理模式)
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub Component component = new ConcreteComponent(); Decorator decorator = new ConcreteDecorator(component); decorator.operate(); }}abstract class Component{ public abstract void operate();}class ConcreteComponent extends Component{ @Override public void operate() { // TODO Auto-generated method stub System.out.println("做的real work!"); } }//抽象的装饰器类abstract class Decorator extends Component{ public Component component; public Decorator(Component component) { // TODO Auto-generated constructor stub this.component = component; } @Override public void operate() { // TODO Auto-generated method stub this.component.operate(); }}//具体的装饰类class ConcreteDecorator extends Decorator{ public ConcreteDecorator(Component component) { super(component); // TODO Auto-generated constructor stub } public void method1() { System.out.println("ConcreteDecorator"); } @Override public void operate() { // TODO Auto-generated method stub method1(); super.operate(); }}
12、策略模式
public class Context { private Strategy strategy = null; public Context(Strategy strategy) { // TODO Auto-generated constructor stub this.strategy = strategy; } public void doAnything() { this.strategy.doSomething(); } public static void main(String[] args) { // TODO Auto-generated method stub Strategy strategy = new ConcreteStrategy1(); Context context = new Context(strategy); context.doAnything(); }}interface Strategy{ public void doSomething();}class ConcreteStrategy1 implements Strategy{ @Override public void doSomething() { // TODO Auto-generated method stub System.out.println("执行策略1"); } }class ConcreteStrategy2 implements Strategy{ @Override public void doSomething() { // TODO Auto-generated method stub System.out.println("执行策略2"); } }
13、适配器模式(适配器需要继承源角色实现目的角色接口)Adaptee-->Adapter-->Target
//场景类public class Client { public static void main(String[] args) { // TODO Auto-generated method stub //原有的业务逻辑 Target target = new ConcreteTarget(); target.request(); //增加了适配器角色后的业务逻辑 Target target2 = new Adapter(); target2.request(); }}//目标角色interface Target{ public void request();}//目标角色的实现类class ConcreteTarget implements Target{ @Override public void request() { // TODO Auto-generated method stub System.out.println("do...something..target"); }}//源角色class Adaptee{ public void doSomething() { System.out.println("do...something..adaptee"); }}//适配器角色class Adapter extends Adaptee implements Target{ @Override public void request() { // TODO Auto-generated method stub super.doSomething(); } }
复杂适配器模式(类关联的方法实现)
//场景类public class Client { public static void main(String[] args) { // TODO Auto-generated method stub //原有的业务逻辑 Target target = new ConcreteTarget(); target.request1(); target.request2(); target.request3(); //增加了适配器角色后的业务逻辑 Adaptee1 adaptee1 = new AdapteeImpl1(); Adaptee2 adaptee2 = new AdapteeImpl2(); Adaptee3 adaptee3 = new AdapteeImpl3(); Target target2 = new Adapter(adaptee1,adaptee2,adaptee3); target2.request1(); target2.request2(); target2.request3(); }}//目标角色interface Target{ public void request1(); public void request2(); public void request3();}//目标角色的实现类class ConcreteTarget implements Target{ @Override public void request1() { // TODO Auto-generated method stub System.out.println("do...something..target1"); } @Override public void request2() { // TODO Auto-generated method stub System.out.println("do...something..target2"); } @Override public void request3() { // TODO Auto-generated method stub System.out.println("do...something..target3"); }}//源角色1interface Adaptee1{ public void doSomething1();}class AdapteeImpl1 implements Adaptee1{ public void doSomething1() { System.out.println("do...something..adaptee1"); }}//源角色2interface Adaptee2{ public void doSomething2();}class AdapteeImpl2 implements Adaptee2{ public void doSomething2() { System.out.println("do...something..adaptee2"); }}//源角色3interface Adaptee3{ public void doSomething3();}class AdapteeImpl3 implements Adaptee3{ public void doSomething3() { System.out.println("do...something..adaptee3"); }}//适配器角色class Adapter implements Target{ private Adaptee1 adaptee1 = null; private Adaptee2 adaptee2 = null; private Adaptee3 adaptee3 = null; public Adapter(Adaptee1 adaptee1, Adaptee2 adaptee2, Adaptee3 adaptee3) { // TODO Auto-generated constructor stub this.adaptee1 = adaptee1; this.adaptee2 = adaptee2; this.adaptee3 = adaptee3; } @Override public void request1() { // TODO Auto-generated method stub adaptee1.doSomething1(); } @Override public void request2() { // TODO Auto-generated method stub adaptee2.doSomething2(); } @Override public void request3() { // TODO Auto-generated method stub adaptee3.doSomething3(); } }
14、组合模式
import java.util.ArrayList;public class Client { public static void main(String[] args) { // TODO Auto-generated method stub Composite root = copositeCorpTree(); System.out.println(display(root)); } public static Composite copositeCorpTree() { //CEO Composite root = new Composite("wa", "总经理", 100000); //三经理 Composite developDep = new Composite("fs", "研发部门经理", 10000); Composite salesDep = new Composite("fgg", "销售部门经理", 20000); Composite financeDep = new Composite("gtr", "财务部经理", 30000); //三个小组组长 Composite firstDevGroup = new Composite("rge", "开发一组组长", 5000); Composite secondDevGroup = new Composite("bbnn", "开发二组组长", 6000); //所有的小兵 Leaf a = new Leaf("a","开发人员",2000); Leaf b = new Leaf("b","开发人员",2000); Leaf c = new Leaf("c","开发人员",2000); Leaf d = new Leaf("d","开发人员",2000); Leaf e = new Leaf("e","开发人员",2000); Leaf f = new Leaf("f","开发人员",2000); Leaf g = new Leaf("g","开发人员",2000); Leaf h = new Leaf("h","销售人员",2000); Leaf i = new Leaf("i","销售人员",2000); Leaf j = new Leaf("j","财务人员",2000); Leaf k = new Leaf("k","CEO秘书",2000); Leaf zhengLaoliu = new Leaf("tht", "研发部副经理", 20000); root.add(k); root.add(developDep); root.add(salesDep); root.add(financeDep); developDep.add(zhengLaoliu); developDep.add(firstDevGroup); developDep.add(secondDevGroup); firstDevGroup.add(a); firstDevGroup.add(b); firstDevGroup.add(c); secondDevGroup.add(d); secondDevGroup.add(e); secondDevGroup.add(f); salesDep.add(h); salesDep.add(i); financeDep.add(j); return root; } public static String display(Composite root) { ArrayListsubordinateList = root.getChildren(); String info = ""; for(Component s:subordinateList) { if(s instanceof Leaf) { info = info + s.doSomething()+"\n"; }else { info = info + "\n" + display((Composite)s); } } return info; }}abstract class Component{ private String name = ""; private String position = ""; private int salary = 0; public Component(String name, String position, int salary) { // TODO Auto-generated constructor stub this.name = name; this.position = position; this.salary = salary; } public String doSomething() { String info = ""; info = "姓名: "+this.name; info = info + "\t职位: "+this.position; info = info + "\t薪水: "+this.salary; return info; }}class Leaf extends Component{ public Leaf(String name, String position, int salary) { super(name, position, salary); // TODO Auto-generated constructor stub } }class Composite extends Component{ ArrayList componentArrayList = new ArrayList<>(); public Composite(String name, String position, int salary) { super(name, position, salary); // TODO Auto-generated constructor stub } public void add(Component component) { this.componentArrayList.add(component); } public ArrayList getChildren(){ return this.componentArrayList; } public void remove(Component component) { this.componentArrayList.remove(component); }}
15、观察者模式
import java.util.Observable;import java.util.Observer;public class Client { public static void main(String[] args) { // TODO Auto-generated method stub ConcreteSubject subject = new ConcreteSubject(); Observer observer1 = new ConcreteObserver1(); Observer observer2 = new ConcreteObserver2(); Observer observer3 = new ConcreteObserver3(); subject.addObserver(observer1); subject.addObserver(observer2); subject.addObserver(observer3); subject.doSomething("aa"); }}//具体被观察者class ConcreteSubject extends Observable{ public void doSomething(String str) { /* * do something */ super.setChanged(); super.notifyObservers(str); }}//具体观察者1class ConcreteObserver1 implements Observer{ @Override public void update(Observable paramObservable, Object paramObject) { // TODO Auto-generated method stub System.out.println("接收到信息,并进行处理1: "+paramObject.toString()); } }//具体观察者2class ConcreteObserver2 implements Observer{ @Override public void update(Observable paramObservable, Object paramObject) { // TODO Auto-generated method stub System.out.println("接收到信息,并进行处理2: "+paramObject.toString()); } }//具体观察者3class ConcreteObserver3 implements Observer{ @Override public void update(Observable paramObservable, Object paramObject) { // TODO Auto-generated method stub System.out.println("接收到信息,并进行处理3: "+paramObject.toString()); } }
16、门面模式
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub Facade facade = new Facade(); facade.methodD(); Facade2 facade2 = new Facade2(); facade2.methodB(); //facade和facade2的权限不一样 }}class ClassA{ public void doSomethingA() { System.out.println("do something A"); }}class ClassB{ public void doSomethingB() { System.out.println("do something B"); }}class ClassC{ public void doSomethingC() { System.out.println("do something C"); }}class Facade{ private ClassA a = new ClassA(); private ClassB b = new ClassB(); private ClassC c = new ClassC(); public void methodA() { this.a.doSomethingA(); } public void methodB() { this.b.doSomethingB(); } public void methodC() { this.c.doSomethingC(); } public void methodD() { this.a.doSomethingA(); this.b.doSomethingB(); this.c.doSomethingC(); }}class Facade2{ private Facade facade = new Facade(); public void methodB() { this.facade.methodB(); }}
17、备忘录模式
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub Originator originator = new Originator(); Caretaker caretaker = new Caretaker(); //创建一个备忘录 caretaker.setMemento(originator.createMemento()); //恢复一个备忘录 originator.restoreMemento(caretaker.getMemento()); }}//发起人角色class Originator{ private String state = ""; public String getState() { return state; } public void setState(String state) { this.state = state; } public Memento createMemento() { return new Memento(this.state); } public void restoreMemento(Memento memento) { this.setState(memento.getState()); }}//备忘录角色class Memento{ private String state = ""; public Memento(String state) { // TODO Auto-generated constructor stub this.state = state; } public String getState() { return state; } public void setState(String state) { this.state = state; } }//备忘录管理员角色class Caretaker{ private Memento memento; public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento = memento; } }
特殊的备忘录模式(类中类)
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub Originator originator = new Originator(); Caretaker caretaker = new Caretaker(); //创建一个备忘录 caretaker.setMemento(originator.createMemento()); //恢复一个备忘录 originator.restoreMemento(caretaker.getMemento()); }}interface IMemento{ }//发起人角色class Originator{ private String state = ""; public String getState() { return state; } public void setState(String state) { this.state = state; } public Memento createMemento() { return new Memento(this.state); } public void restoreMemento(IMemento memento) { this.setState(((Memento)memento).getState()); } //备忘录角色 private class Memento implements IMemento{ private String state = ""; public Memento(String state) { // TODO Auto-generated constructor stub this.state = state; } public String getState() { return state; } public void setState(String state) { this.state = state; } }}//备忘录管理员角色class Caretaker{ private IMemento memento; public IMemento getMemento() { return memento; } public void setMemento(IMemento memento) { this.memento = memento; } }
18、访问者模式
import java.util.Random;public class Client { public static void main(String[] args) { // TODO Auto-generated method stub for(int i=0;i<10;++i) { Element el = ObjectStruture.createElement(); el.accept(new Visitor()); } }}abstract class Element{ public abstract void doSomething(); public abstract void accept(IVisitor visitor);}class ConcreteElement1 extends Element{ @Override public void doSomething() { // TODO Auto-generated method stub System.out.println("this is ConcreteElement1!"); } @Override public void accept(IVisitor visitor) { // TODO Auto-generated method stub visitor.visit(this); } }class ConcreteElement2 extends Element{ @Override public void doSomething() { // TODO Auto-generated method stub System.out.println("this is ConcreteElement2!"); } @Override public void accept(IVisitor visitor) { // TODO Auto-generated method stub visitor.visit(this); } }interface IVisitor{ public void visit(ConcreteElement1 e11); public void visit(ConcreteElement2 e12);}class Visitor implements IVisitor{ @Override public void visit(ConcreteElement1 e11) { // TODO Auto-generated method stub e11.doSomething(); } @Override public void visit(ConcreteElement2 e12) { // TODO Auto-generated method stub e12.doSomething(); } }class ObjectStruture{ public static Element createElement() { Random rand = new Random(); if(rand.nextInt(100)>50) { return new ConcreteElement1(); }else { return new ConcreteElement2(); } }}
19、状态模式
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub Context context = new Context(); context.setCurrentState(Context.STATE1); context.handle2(); context.handle1(); }}abstract class State{ protected Context context; public void setContext(Context context) { this.context = context; } public abstract void handle1(); public abstract void handle2();}class ConcreteState1 extends State{ @Override public void handle1() { // TODO Auto-generated method stub System.out.println("执行handle1了!"); } @Override public void handle2() { // TODO Auto-generated method stub super.context.setCurrentState(Context.STATE2); super.context.handle2(); } }class ConcreteState2 extends State{ @Override public void handle1() { // TODO Auto-generated method stub super.context.setCurrentState(Context.STATE1); super.context.handle1(); } @Override public void handle2() { // TODO Auto-generated method stub System.out.println("执行handle2了!"); } }class Context{ public final static State STATE1 = new ConcreteState1(); public final static State STATE2 = new ConcreteState2(); private State currentState; public State getCurrentState() { return currentState; } public void setCurrentState(State currentState) { this.currentState = currentState; this.currentState.setContext(this); } public void handle1() { this.currentState.handle1(); } public void handle2() { this.currentState.handle2(); }}
20、解释器模式
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Stack;public class Client { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub String expStr = getExpstr(); HashMapvar = getValue(expStr); Calculator cal = new Calculator(expStr); System.out.println("运算结果为:"+expStr + "=" + cal.run(var)); } public static String getExpstr() throws IOException{ System.out.print("请输入表达式:"); return (new BufferedReader(new InputStreamReader(System.in))).readLine(); } public static HashMap getValue(String exprStr)throws IOException{ HashMap map = new HashMap<>(); for(char ch:exprStr.toCharArray()) { if(ch != '+' && ch != '-') { if(!map.containsKey(String.valueOf(ch))) { System.out.print("请输入"+ch+"的值:"); String in = (new BufferedReader(new InputStreamReader(System.in))).readLine(); map.put(String.valueOf(ch), Integer.valueOf(in)); } } } return map; }}abstract class Expression{ public abstract int interpreter(HashMap var);}class VarExpression extends Expression{ private String key; public VarExpression(String key) { this.key = key; } @Override public int interpreter(HashMap var) { // TODO Auto-generated method stub return var.get(this.key); } }abstract class SymbolExpression extends Expression{ protected Expression left; protected Expression right; public SymbolExpression(Expression left, Expression right) { this.left = left; this.right = right; }}class AddExpression extends SymbolExpression{ public AddExpression(Expression left, Expression right) { super(left, right); // TODO Auto-generated constructor stub } @Override public int interpreter(HashMap var) { // TODO Auto-generated method stub return super.left.interpreter(var) + super.right.interpreter(var); } }class SubExpression extends SymbolExpression{ public SubExpression(Expression left, Expression right) { super(left, right); // TODO Auto-generated constructor stub } @Override public int interpreter(HashMap var) { // TODO Auto-generated method stub return super.left.interpreter(var) - super.right.interpreter(var); } }class Calculator{ private Expression expression; public Calculator(String expStr) { Stack stack = new Stack<>(); char[] charArray = expStr.toCharArray(); Expression left = null; Expression right = null; for(int i=0;i var) { return this.expression.interpreter(var); }}
21、桥梁模式(抽象与实现相互分离,比继承优势大得多)
//场景类 public class Client { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Abstraction abs = new RefinedAbstraction(new ConcreteImplementor1()); abs.request(); abs = new RefinedAbstraction(new ConcreteImplementor2()); abs.request(); } } //实现化角色interface Implementor{ public void doSomething(); public void doAnything();} //具体实现化角色class ConcreteImplementor1 implements Implementor{ @Override public void doSomething() { // TODO Auto-generated method stub System.out.println("doSomething--1"); } @Override public void doAnything() { // TODO Auto-generated method stub System.out.println("doAnything--1"); } }class ConcreteImplementor2 implements Implementor{ @Override public void doSomething() { // TODO Auto-generated method stub System.out.println("doSomething--2"); } @Override public void doAnything() { // TODO Auto-generated method stub System.out.println("doAnything--2"); } } //抽象化角色abstract class Abstraction{ private Implementor imp; public Abstraction(Implementor imp) { this.imp = imp; } public void request() { this.imp.doSomething(); } public void response() { this.imp.doAnything(); } public Implementor getImp() { return this.imp; }} //具体抽象化角色class RefinedAbstraction extends Abstraction{ public RefinedAbstraction(Implementor imp) { super(imp); // TODO Auto-generated constructor stub } @Override public void request() { // TODO Auto-generated method stub super.request(); super.response(); } }