本文主要是介绍外观模式-Facade/中介者模式-Mediator,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
外观模式主要解决:降低访问复杂系统的内部子系统时的复杂度,简化客户端之间的接口。
中介者模式主要解决:对象与对象之间存在大量的关联关系,这样势必会导致系统的结构变得很复杂,同时若一个对象发生改变,我们也需要跟踪与之相关联的对象,同时做出相应的处理。
外观模式
public class CPU {public void startup(){System.out.println("cpu startup!");}public void shutdown(){System.out.println("cpu shutdown!");}
}public class Memory {public void startup(){System.out.println("memory startup!");}public void shutdown(){System.out.println("memory shutdown!");}
}public class Disk {public void startup(){System.out.println("disk startup!");}public void shutdown(){System.out.println("disk shutdown!");}
}public class Computer {private CPU cpu;private Memory memory;private Disk disk;public Computer(){cpu = new CPU();memory = new Memory();disk = new Disk();}public void startup(){System.out.println("start the computer!");cpu.startup();memory.startup();disk.startup();System.out.println("start computer finished!");}public void shutdown(){System.out.println("begin to close the computer!");cpu.shutdown();memory.shutdown();disk.shutdown();System.out.println("computer closed!");}
}public class User {public static void main(String[] args) {Computer computer = new Computer();computer.startup();computer.shutdown();}
}
中介者模式
public class MediatorPattern {public static void main(String[] args) {Mediator md = new ConcreteMediator();Colleague c1, c2;c1 = new ConcreteColleague1();c2 = new ConcreteColleague2();md.register(c1);md.register(c2);c1.send();System.out.println("-------------");c2.send();}
}//抽象中介者
public abstract class Mediator {public abstract void register(Colleague colleague);public abstract void relay(Colleague cl); //转发
}//具体中介者
public class ConcreteMediator extends Mediator {private List<Colleague> colleagues = new ArrayList<Colleague>();public void register(Colleague colleague) {if (!colleagues.contains(colleague)) {colleagues.add(colleague);colleague.setMedium(this);}}public void relay(Colleague cl) {for (Colleague ob : colleagues) {if (!ob.equals(cl)) {((Colleague) ob).receive();}}}
}//抽象同事类
public abstract class Colleague {protected Mediator mediator;public void setMedium(Mediator mediator) {this.mediator = mediator;}public abstract void receive();public abstract void send();
}//具体同事类
public class ConcreteColleague1 extends Colleague {public void receive() {System.out.println("具体同事类1收到请求。");}public void send() {System.out.println("具体同事类1发出请求。");mediator.relay(this); //请中介者转发}
}//具体同事类
public class ConcreteColleague2 extends Colleague {public void receive() {System.out.println("具体同事类2收到请求。");}public void send() {System.out.println("具体同事类2发出请求。");mediator.relay(this); //请中介者转发}
}
这篇关于外观模式-Facade/中介者模式-Mediator的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!