简介
首先,在写装饰模式的代码之前呢,我想要捋一下,比如说你想装饰一辆车,那么首先,你得抽象一下车这个总体的接口来制造车对应的类型,然后通过一个实现类来创建一个品牌,除此之外,因为车可能有很多都是相同的,所以我们可以创建一个统一的类,然后根据不同的车子,来设置对应的show方法,然后再继承这个类,重写里面的方法之后,再进行调用
package jianzaozhe;
public interface Car {
public void show();
}
package jianzaozhe;
public class Benz implements Car{
@Override
public void show() {
System.out.println("奔驰的默认颜色是黑色");
}
}
package jianzaozhe;
public class CarDecorator implements Car{
private Car car=null;
public CarDecorator(Car car){
this.car=car;
}
public void show(){
this.car.show();
}
}
package jianzaozhe;
public class ConcreteCarDecorator extends CarDecorator{
public ConcreteCarDecorator(Car car){
super(car);
}
private void print(){
System.out.println("颜色是紫霞");
}
private void setGps(){
System.out.println("安装定位GpS系统");
}
public void show(){
super.show();
this.print();
this.setGps();
}
}
package jianzaozhe;
public class CilentDemo {
public static void main(String[] args) {
Car car=new Benz();
CarDecorator cd=new ConcreteCarDecorator(car);
cd.show();
}
}
结果:
|