设计模式需要遵循的原则:
一、单一职责原则
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、单例模式(扩展:固定数量多例模式)
class SinglePattern { private static final SinglePattern instance = new SinglePattern(); private SinglePattern() { } public static SinglePattern getInstance() { return instance; } } class SinglePattern2 { private static volatile SinglePattern2 instance = null; private SinglePattern2() { } public static SinglePattern2 getInstance() { if (instance == null) { synchronized (SinglePattern2.class) { if (instance == null) { instance = new SinglePattern2(); } } } return instance; } }
2、工厂方法模式(在client代码中出现了产品的实现类)
定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。
public class Main{ public static void main(String[] args) { AbstractFactory factory = new Factory(); AbstarctProducer producer = factory.createProduct(Producer.class); producer.method(); } } abstract class AbstractFactory { public abstract <T extends AbstarctProducer> T createProduct(Class<T> clazz); } class Factory extends AbstractFactory{ @Override public <T extends AbstarctProducer> T createProduct(Class<T> clazz) { // TODO Auto-generated method stub try { return (T)Class.forName(clazz.getName()).newInstance(); } catch (Exception e) { e.printStackTrace(); } return null; } } abstract class AbstarctProducer{ public abstract void method(); } class Producer extends AbstarctProducer{ @Override public void method() { System.out.println("AA"); } }
静态工厂模式(简单工厂模式)
public class Main{ public static void main(String[] args) { AbstarctProducer producer = Factory.createProduct(Producer.class); producer.method(); } } class Factory { public static <T extends AbstarctProducer> T createProduct(Class<T> clazz) { // TODO Auto-generated method stub try { return (T)Class.forName(clazz.getName()).newInstance(); } catch (Exception e) { e.printStackTrace(); } return null; } } abstract class AbstarctProducer{ public abstract void method(); } class Producer extends AbstarctProducer{ @Override public void method() { System.out.println("AA"); } }
负责产生单例的工厂类
延迟加载的工厂类
3、抽象工厂模式(在client类中不会出现产品的具体实现类)
public class Main{ public static void main(String[] args) { HumanFactory yellowHumanFactory = new YellowFactory(); Human yellowHuman = yellowHumanFactory.createHuman(); yellowHuman.getColor(); HumanFactory whiteHumanFactory = new WhiteFactory(); Human whiteHuman = whiteHumanFactory.createHuman(); whiteHuman.getColor(); } } //抽象工厂接口,由接口的实现类决定具体的工厂类 //HumanFactory(抽象工厂)---->工厂实现类 //Human(抽象类)------------->类的实现类 interface HumanFactory{ public Human createHuman(); } class YellowFactory implements HumanFactory{ @Override public Human createHuman() { return new YellowHuman(); } } class WhiteFactory implements HumanFactory{ @Override public Human createHuman() { return new WhiteHuman(); } } interface Human{ public void getColor(); } class WhiteHuman implements Human{ public void getColor() { System.out.println("White Color!"); } } class YellowHuman implements Human{ public void getColor() { System.out.println("Yellow Color!"); } }
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 ArrayList<String> sequence = new ArrayList<>(); protected abstract void start(); protected abstract void stop(); protected abstract void alarm(); public final void run() { for(int i=0;i<sequence.size();++i) { String actionName = this.sequence.get(i); if("start".equalsIgnoreCase(actionName)) { this.start(); }else if("alarm".equalsIgnoreCase(actionName)) { this.alarm(); }else if("stop".equalsIgnoreCase(actionName)) { this.stop(); } } } public final void setSequence(ArrayList<String> sequence){ this.sequence = sequence; } } abstract class CarBuilder{ public abstract void setSequence(ArrayList<String> sequence); public abstract AbstractCreateCar getCarModel(); } class BWMBuilder extends CarBuilder{ private CreateBWM bwm = new CreateBWM(); @Override public void setSequence(ArrayList<String> 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<String> 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<String> 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 Main{ public static void main(String[] args) { Human human = new HumanImpl(); Human humanProxy = new ProxyHuman(human); humanProxy.show(); } } interface Human{ void show(); } class HumanImpl implements Human{ @Override public void show() { System.out.println("HumanImpl!"); } } class ProxyHuman implements Human{ private Human human; public ProxyHuman(Human human) { this.human = human; } @Override public void show() { System.out.println("before!"); human.show(); System.out.println("after!"); } }
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()<number) { super.purchase.buyIBMcomputer(number); } super.stock.decrease(number); } private void offSell() { System.out.println("折价销售IBM电脑"+stock.getStockNumber()+"台"); } private void clearStock() { super.sale.offSale(); super.purchase.refuseBuyIBM(); } } //中介者抽象类 abstract class AbstarctMediaer{ protected Purchase purchase; protected Sale sale; protected Stock stock; public AbstarctMediaer() { purchase = new Purchase(this); sale = new Sale(this); stock = new Stock(this); } public abstract void execute(String str, Object...objects ); } abstract class AbstractColleague{ protected AbstarctMediaer mediaer; public AbstractColleague(AbstarctMediaer mediaer) { this.mediaer = mediaer; } } class Purchase extends AbstractColleague{ public Purchase(AbstarctMediaer mediaer) { super(mediaer); // TODO Auto-generated constructor stub } public void buyIBMcomputer(int number) { super.mediaer.execute("purchase.buy", number); } public void refuseBuyIBM() { System.out.println("不再购买IBM电脑"); } } class Sale extends AbstractColleague{ public Sale(AbstarctMediaer mediaer) { super(mediaer); // TODO Auto-generated constructor stub } public void sellIBMComputer(int number) { super.mediaer.execute("sale.sell", number); System.out.println("销售IBM电脑"+number+"台"); } public int getSaleStatus() { Random rand = new Random(System.currentTimeMillis()); int saleStatus = rand.nextInt(100); System.out.println("IBM电脑的销售情况为: "+saleStatus); return saleStatus; } public void offSale() { super.mediaer.execute("sale.offsell"); } } class Stock extends AbstractColleague{ public Stock(AbstarctMediaer mediaer) { super(mediaer); // TODO Auto-generated constructor stub } private static int COMPUTER_NUMBER = 100; public void increase(int number) { COMPUTER_NUMBER = COMPUTER_NUMBER + number; System.out.println("库存数量为: "+COMPUTER_NUMBER); } public void decrease(int number) { COMPUTER_NUMBER = COMPUTER_NUMBER - number; System.out.println("库存数量为: "+COMPUTER_NUMBER); } public int getStockNumber() { return COMPUTER_NUMBER; } public void clearStock() { System.out.println("清理存货数量为: "+COMPUTER_NUMBER); super.mediaer.execute("stock.clear"); } }
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"); } } //源角色1 interface Adaptee1{ public void doSomething1(); } class AdapteeImpl1 implements Adaptee1{ public void doSomething1() { System.out.println("do...something..adaptee1"); } } //源角色2 interface Adaptee2{ public void doSomething2(); } class AdapteeImpl2 implements Adaptee2{ public void doSomething2() { System.out.println("do...something..adaptee2"); } } //源角色3 interface 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) { ArrayList<Component> subordinateList = root.getChildren(); String info = ""; for(Component s:subordinateList) { if(s instanceof Leaf) { info = info + s.doSomething()+" "; }else { info = info + " " + 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 + " 职位: "+this.position; info = info + " 薪水: "+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<Component> 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<Component> 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); } } //具体观察者1 class ConcreteObserver1 implements Observer{ @Override public void update(Observable paramObservable, Object paramObject) { // TODO Auto-generated method stub System.out.println("接收到信息,并进行处理1: "+paramObject.toString()); } } //具体观察者2 class ConcreteObserver2 implements Observer{ @Override public void update(Observable paramObservable, Object paramObject) { // TODO Auto-generated method stub System.out.println("接收到信息,并进行处理2: "+paramObject.toString()); } } //具体观察者3 class 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(); HashMap<String, Integer> var = 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<String, Integer> getValue(String exprStr)throws IOException{ HashMap<String, Integer> 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<String, Integer> var); } class VarExpression extends Expression{ private String key; public VarExpression(String key) { this.key = key; } @Override public int interpreter(HashMap<String, Integer> 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<String, Integer> 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<String, Integer> 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<Expression> stack = new Stack<>(); char[] charArray = expStr.toCharArray(); Expression left = null; Expression right = null; for(int i=0;i<charArray.length;++i) { switch(charArray[i]) { case '+': left = stack.pop(); right = new VarExpression(String.valueOf(charArray[++i])); stack.push(new AddExpression(left, right)); break; case '-': left = stack.pop(); right = new VarExpression(String.valueOf(charArray[++i])); stack.push(new SubExpression(left, right)); break; default: stack.push(new VarExpression(String.valueOf(charArray[i]))); } } this.expression = stack.pop(); } public int run(HashMap<String, Integer> 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(); } }