首页 > 代码库 > Java设计模式(五)外观模式 桥梁模式

Java设计模式(五)外观模式 桥梁模式

(九)外观模式

外观模式为子系统提供一个接口,便于使用。解决了类与类之间关系的,外观模式将类之间的关系放在一个 Facade 类中,降低了类类之间的耦合度,该模式不涉及接口。

class CPU {
	public void startup(){
		System.out.println("cpu start");
	}
	public void shutdown(){
		System.out.println("cpu stop");
	}
}
class Memory {
	public void startup(){
		System.out.println("Memory start");
	}
	public void shutdown(){
		System.out.println("Memory stop");
	}
}
class Disk {
	public void startup(){
		System.out.println("Disk start");
	}
	public void shutdown(){
		System.out.println("Disk stop");
	}
}
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 Facade {
	public static void main(String[] args){
		Computer computer = new Computer();
		computer.startup(); 
		computer.shutdown();
	}
}
外观模式将表现层与逻辑层隔离,封装底层的复杂处理,为用户提供简单的接口。
(十)桥梁模式 Bridge

桥梁模式就是吧事物和具体的实现分开,将抽象与抽象方法的实现相互分离来实现解耦,以便两者能够相互独立的变化。

interface Fruit{
	public void method();
}
class Apple implements Fruit{
	public void method(){
		System.out.println("Apple");
	}
}
class Pear implements Fruit{
	public void method(){
		System.out.println("Pear");
	}
}
abstract class Bridge{
	private Fruit fruit;
	public void method(){
		fruit.method();
	}
	public Fruit getFruit(){
		return fruit;
	}
	public void setFruit(Fruit fruit){
		this.fruit = fruit;
	}
}
class MyBridge extends Bridge{
	public void method(){
		getFruit().method();
	}
}
public class BridgeTest {
	public static void main(String[] args){
		Bridge bridge = new MyBridge();
		Fruit apple = new Apple();
		bridge.setFruit(apple);
		bridge.method();
		
		Fruit pear = new Pear();
		bridge.setFruit(pear);
		bridge.method();
	}
}