代理模式 自己写的
package test;
public interface Person {
public void work();
}
package test;
public class People implements Person{
public void work() {
System.out.println("People work()");
}
}
package test;
public interface Study {
public void study();
}
package test;
public class GoodStudy implements Study{
public void study() {
System.out.println("goodstudy study()");
}
}
适配器:
package test;
public class Adapter implements Person{
private Study study ;
private Person person ;
public Adapter(Study study2){
this.study = study2;
}
public Adapter(People people){
this.person = person;
}
public Adapter(Study study, Person person) {
super();
this.study = study;
this.person = person;
}
public void work() {
System.out.println("adapter work()");
person.work();
study.study();
}
}
package test;
public class AdapterTest {
public static void main(String[] args) {
Person person = new Adapter(new GoodStudy(),new People());
person.work();
}
}
结果:
adapter work() People work() goodstudy study()
Person为新功能 study是需要适配的功能
双向适配器
package test;
public class AdapterTwo implements Person , Study {
private Person person;
private Study study;
public AdapterTwo(Person person, Study study) {
super();
this.person = person;
this.study = study;
}
public void study() {
person.work();
}
public void work() {
study.study();
}
}
package test;
import org.junit.Test;
public class AdapterTest {
@Test
public void test() {
Person person = new Adapter(new GoodStudy(),new People());
person.work();
输出:
adapter work()
People work()
goodstudy study()
}
@Test
public void test2(){
Person person = new AdapterTwo(new People(),new GoodStudy());
person.work();
输出:goodstudy study()
} }
类适配器
package test;
import org.junit.Test;
public class AdapterClass extends GoodStudy implements Person {
public void work() {
this.study();
}
@Test
public void test(){
//方式1
AdapterClass adapterClass = new AdapterClass();
adapterClass.work();
//方式2
work();
} }
结果:
goodstudy study()

浙公网安备 33010602011771号