1. 场景
需要为已经设计好的类添加新的职责
又称包装 (Wrapper) 模式, 是以对客户端透明的方式扩展对象的功能
是继承关系的一个替代方案, 对客户端透明意味着接口不变
2. 角色
2-1. 抽象构件: 原始的功能接口
2-2. 具体构件: 原始的具体实现类
2-3. 装饰角色: 持有具体构件类的对象, 以便执行原有功能
2-4. 具体装饰: 具体扩展的功能实现类
3-3. 实例
// 原始的功能接口
public interface Component {
void operation();
}
// 原始的具体实现类
public class ConcreteComponent implements Component {
public void operation() {
System.out.println("I'm " + this.getClass().getName());
}
}
// 装饰角色
public class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
// 具体装饰
public class BeforeDecorator extends Decorator {
public BeforeDecorator(Component component) {
super(component);
}
public void operation() {
before();
super.operation();
}
private void before() {
System.out.println("before: I'm "+this.getClass().getName());
}
}
// 客户端
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
component.operation(); // 原来调用方式
System.out.println("----------------------------------------");
component = new BeforeDecorator(new ConcreteComponent());
component.operation(); // 装饰后的调用方式, 对客户端接口不变
}
}
需要为已经设计好的类添加新的职责
又称包装 (Wrapper) 模式, 是以对客户端透明的方式扩展对象的功能
是继承关系的一个替代方案, 对客户端透明意味着接口不变
2. 角色
2-1. 抽象构件: 原始的功能接口
2-2. 具体构件: 原始的具体实现类
2-3. 装饰角色: 持有具体构件类的对象, 以便执行原有功能
2-4. 具体装饰: 具体扩展的功能实现类
3-3. 实例
// 原始的功能接口
public interface Component {
void operation();
}
// 原始的具体实现类
public class ConcreteComponent implements Component {
public void operation() {
System.out.println("I'm " + this.getClass().getName());
}
}
// 装饰角色
public class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
// 具体装饰
public class BeforeDecorator extends Decorator {
public BeforeDecorator(Component component) {
super(component);
}
public void operation() {
before();
super.operation();
}
private void before() {
System.out.println("before: I'm "+this.getClass().getName());
}
}
// 客户端
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
component.operation(); // 原来调用方式
System.out.println("----------------------------------------");
component = new BeforeDecorator(new ConcreteComponent());
component.operation(); // 装饰后的调用方式, 对客户端接口不变
}
}
0 件のコメント:
コメントを投稿