结构型模式---适配器模式和装饰器模式
·
适配器模式:当一个类需要的接口实现和当前使用的不一致时,就需要一个第三方类充当适配器,来让由于接口不兼容而不能一起工作的那些类能一起工作。
类适配器模式:类适配器模式违背了合成复用原则。类适配器在有接口规范的情况下可用,反之不可用。
- 定义一个类,实现适配目标的类的接口,重写里面的方法,同时继承要适配的类,在重写的方法里面调用它的方法,把用过适配器类来使用目标对象
对象适配器模式:可以通过继承或者实现的方式,不需要适配目标有接口,满足合成复用原则
- 实现适配目标类的接口,当目标没有接口的时候可以使用继承,在类中定义要适配的类或接口,在重写的方法中使用它
接口适配器模式:当不希望实现一个接口中所有的方法时,可以创建一个抽象类Adapter ,实现所有方法。而此时我们只需要继承该抽象类即可
装饰者模式:装饰者模式可以带来比继承更加灵活性的扩展功能,比继承更具良好的扩展性,装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
/**
* 抽象构建类 用抽象方法规范接受附加的对象
* 装饰者模式,使用上实际是存在两个类,一个具体构建类,里面是原始方法,一个是装饰者类,增强的方法
* 在具体装饰者类中对两个类进行赋值,通过一个方法来一起调用它们两个具体方法
*/
public abstract class AbsComponent {
private Integer age;
public AbsComponent(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public abstract Integer age();
}
/**
* 具体构建,实现了具体的方法
*/
public class ConcretComponent extends AbsComponent{
public ConcretComponent(Integer age) {
super(age);
}
@Override
public Integer age() {
return getAge();
}
}
/**
* 装饰者类
*/
public abstract class Garnish extends AbsComponent{
private AbsComponent absComponent;
public Garnish(Integer age, AbsComponent absComponent) {
super(age);
this.absComponent = absComponent;
}
@Override
public Integer age() {
return absComponent.getAge();
}
}
public class ConcretGarnish extends Garnish{
//给两个对象赋值
public ConcretGarnish(AbsComponent absComponent) {
super(10, absComponent);
}
public Integer getAge(){
//一个是成员对象的值,一个是具体构建的值,把它们相加
return age()+super.getAge();
}
}
/**
* 具体装饰者类 调用了两个对象的方法
*/
public class ConcretGarnish extends Garnish{
//给两个对象赋值
public ConcretGarnish(AbsComponent absComponent) {
super(10, absComponent);
}
public Integer getAge(){
//一个是成员对象的值,一个是具体构建的值,把它们相加
return age()+super.getAge();
}
}
public class TestGarnish {
public static void main(String[] args) {
/**
* 和代理模式的不同在于装饰者模式可以一直这样递归相加下去,代理模式只能执行一次
*/
AbsComponent concretComponent = new ConcretComponent(11);
System.out.println(concretComponent.getAge());//11
concretComponent = new ConcretGarnish(concretComponent);
System.out.println(concretComponent.getAge());//21
//相当于new ConcretGarnish(new ConcretGarnish(new ConcretComponent(11))),所以是31
concretComponent = new ConcretGarnish(concretComponent);
System.out.println(concretComponent.getAge());//31
}
}
更多推荐
所有评论(0)