Java设计模式之适配器模式

来源:互联网 发布:俞永福 知乎 编辑:程序博客网 时间:2024/05/18 00:14

适配器模式:

1,类适配器模式

源角色(Adaptee):

package com.classadpter;
public class Adaptee {
    public void code(){
        System.out.println("能写代码");
    }
}

目标抽象角色(Target):

package com.classadpter;
public interface Target {
    public void code();
    public void pm();
}

适配器角色(Adapter)

package com.classadpter;
//Adpter:就是继承Target,继承Adaptee
public class Adapter extends Adaptee implements Target {
//这里这个IT民工即能写代码,也想能做产品,话说好多coder都喜欢这么yy来着
    @Override
    public void pm() {
        // TODO Auto-generated method stub
        System.out.println("还能做产品");
    }
    
    
    public void work(){
        this.code();
        this.pm();
    }
    
    public static void main(String[] args) {
        
        Adapter adapter = new Adapter();
        adapter.work();
    
    }

}

test result:

能写代码
还能做产品



2,对象适配器模式

源角色(Adaptee):

package com.objectadapter;
public class Adaptee {
    public void code(){
        System.out.println("能写代码");
    }
}

目标抽象角色(Target):

package com.objectadapter;
public interface Target {
    public void code();
    public void pm();
}


适配器角色(Adapter)

package com.objectadapter;

//Adpter:就是继承Target,继承Adaptee
public class Adapter implements Target {
    public Adaptee adaptee ;
//这里这个IT民工即能写代码,也能做产品,话说好多coder都喜欢这么yy来着
    public Adapter(Adaptee adaptee){
        this.adaptee = adaptee;
    }
    
    public void code() {
        // TODO Auto-generated method stub
        this.adaptee.code();
    }
    
    public void pm() {
        System.out.println("我还能做产品");
    }
    
    public void work(){
        this.code();
        this.pm();
    }
    
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Adapter adapter = new Adapter(adaptee);
        adapter.work();
    
    }

}