您的位置:首页 > 其它

设计模式学习之适配器与外观模式

2014-07-26 21:26 381 查看
定义:适配器模式将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。

适配器(Adapter)分为“对象(Object)”适配器和“类(Class)”适配器两种。 
在类适配器中,适配器继承了目标(Target)和被适配者(Adaptee);而对象适配器中,适配器利用组合的方式将请求传送给被适配者。

实例

让List类型支持枚举类型

public class ListEnumeration implements Enumeration {  

    private List list;  

    public ListEnumeration(List al) {  

        this.list = al;  

    }  

    public boolean hasMoreElements() {  

        return list.iterator().hasNext();  

    }  

    public Object nextElement() {  

        return list.iterator().next();  

    }  

}

外观模式提供了一个统一的接口,用来访问子系统中的一群接口。外观定义了一个高层接口,让子系统更容易使用。

结构图如下:



适用性:  
1 .为一个复杂子系统提供一个简单接口。
2 .提高子系统的独立性。
3 .在层次化结构中,可以使用 Facade 模式定义系统中每一层的入口。

实例:
// 电源  
public class Power {  
    public void connect() {  
        System.out.println("The power is connected.");  
    }  
    public void disconnect() {  
        System.out.println("The power is disconnected.");  
    }  
}  
// 主板  
public class MainBoard {  
    public void on() {  
        System.out.println("The mainboard is on.");  
    }  
  
    public void off() {  
        System.out.println("The mainboard is off.");  
    }  
}  
// 硬盘  
public class HardDisk {  
    public void run() {  
        System.out.println("The harddisk is running.");  
    }  
  
    public void stop() {  
        System.out.println("The harddisk is stopped.");  
    }  
}   
// 操作系统  
public class OperationSystem {  
    public void startup() {  
        System.out.println("The opertion system is startup.");  
    }  
  
    public void shutdown() {  
        System.out.println("The operation system is shutdown.");  
    }  
}  
// 计算机外观  
public class Computer {  
    private Power power;  
  
    private MainBoard board;  
  
    private HardDisk disk;  
  
    private OperationSystem system;  
  
    public Computer(Power power, MainBoard board, HardDisk disk, OperationSystem system) {  
        this.power = power;  
        this.board = board;  
        this.disk = disk;  
        this.system = system;  
    }  
  
    public void startup() {  
        this.power.connect();  
        this.board.on();  
        this.disk.run();  
        this.system.startup();  
    }  
  
    public void shutdown() {  
        this.system.shutdown();  
        this.disk.stop();  
        this.board.off();  
        this.power.disconnect();  
    }  
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息