📄 client.java
字号:
/*
* Created on 2005-5-11
* 意图 动态地给一个对象添加一些额外的职责。
* 就增加功能来说,Decorator 模式相比生成子类更为灵活。
* 适用性 在不影响其他对象的情况下,以动态、透明的方式
* 给单个对象添加职责。处理那些可以撤消的职责。
* 当不能采用生成子类的方法进行扩充时。
* 一种情况是,可能有大量独立的扩展,为支持每一种
* 组合将产生大量的子类,使得子类数目呈爆炸性增长。
* 另一种情况可能是因为类定义被隐藏,或类定义不能
* 用于生成子类。
*/
package com.test.pattern.struct.decorator;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
abstract class Component {
public abstract void Draw();
}
class ConcreteComponent extends Component {
private String strName;
public ConcreteComponent(String s) {
strName = s;
}
public void Draw() {
System.out.println("ConcreteComponent - " + strName);
}
}
abstract class Decorator extends Component {
protected Component ActualComponent;
public void SetComponent(Component c) {
ActualComponent = c;
}
public void Draw() {
if (ActualComponent != null)
ActualComponent.Draw();
}
}
class ConcreteDecorator extends Decorator {
private String strDecoratorName;
public ConcreteDecorator(String str) {
// how decoration occurs is localized inside this decorator
// For this demo, we simply print a decorator name
strDecoratorName = str;
}
public void Draw() {
CustomDecoration();
super.Draw();
}
void CustomDecoration() {
System.out.println("In ConcreteDecorator: decoration goes here");
System.out.println(strDecoratorName);
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client {
Component Setup() {
ConcreteComponent c = new ConcreteComponent(
"This is the real component");
ConcreteDecorator d = new ConcreteDecorator(
"This is a decorator for the component");
d.SetComponent(c);
return d;
}
public static void main(String[] args) {
Client client = new Client();
Component c = client.Setup();
// The code below will work equally well with the real component,
// or a decorator for the component
c.Draw();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -