Attach additional responsibilities to an object dynamically keeping the same interface.Decorators provide a flexible alternative to subclassing for extending functionality.
动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式比生成子类更为灵活。
抽象构建角色(Component):该角色用于规范需要装饰的对象(原始对象)。
package com.DesignPattern.Structural.Decorator;
public interface Component {
public void operation();
}
package com.DesignPattern.Structural.Decorator;
public class ConcreteComponent implements Component {
@Override
public void operation() {
// 业务代码
System.out.println("concreteComponent opration");
}
}
装饰角色(Decorator):该角色持有一个构件对象的实例,并定义一个与抽象构件接口一致的接口。
package com.DesignPattern.Structural.Decorator;
public abstract class Decorator implements Component {
private Component component=null;
public Decorator(Component component){
this.component=component;
}
@Override
public void operation() {
this.component.operation();
}
}
具体修饰角色(Concrete Decorator):该角色负责对构件对象进行装饰。
package com.DesignPattern.Structural.Decorator;
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
//自己定义的方法
private void method(){
System.out.println("add decorator method");
}
//重写operation方法
public void operation(){
this.method();
super.operation();
}
}
Client.java
package com.DesignPattern.Structural.Decorator;
public class Client {
public static void main(String[] args){
Component component=new ConcreteComponent();
//进行装饰
component=new ConcreteDecorator(component);
component.operation();
}
}
装饰模式的实例
Car.java
package com.DesignPattern.Structural.Decorator;
//汽车接口
public interface Car {
// 车的装配
public void show();
}
Benz.java
package com.DesignPattern.Structural.Decorator;
//奔驰车(裸车,需要装饰)
public class Benz implements Car {
@Override
public void show() {
System.out.println("Benz default color is black");
}
}
CarDecorator.java
package com.DesignPattern.Structural.Decorator;
//汽车装饰(抽象装饰)
public abstract class CarDecorator implements Car {
private Car car = null;
public CarDecorator(Car car) {
this.car = car;
}
@Override
public void show() {
this.car.show();
}
}
ConcreteCarDecorator.java
package com.DesignPattern.Structural.Decorator;
//具体汽车修饰
public class ConcreteCarDecorator extends CarDecorator {
public ConcreteCarDecorator(Car car) {
super(car);
}
// 给车彩绘
private void print() {
System.out.println("print on car");
}
// 给车安装GPS
private void setGps() {
System.out.println("install GPS");
}
// 重写show()方法
public void show() {
super.show();
this.print();
this.setGps();
}
}
ClientDemo.java
package com.DesignPattern.Structural.Decorator;
public class ClientDemo {
public static void main(String[] args) {
Car car = new Benz();
// 对奔驰车进行装饰
CarDecorator cd = new ConcreteCarDecorator(car);
cd.show();
}
}
装饰模式 Decorator PatternAttach additional responsibilities to an object dynamically keeping the same interface.Decorators provide a flexible alternative to subclassing for extending functionality.动态地给一个对