《大话设计模式》阅读笔记和总结。原书是C#编写的,本人用Java实现了一遍,包括每种设计模式的UML图实现和示例代码实现。
目录:设计模式
Github地址:DesignPattern
说明
定义:装饰模式(Decorator)动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
UML图:
装饰模式UML图.png代码实现:
Component类
abstract class Component {
public abstract void operation();
}
ConcreteComponent类
class ConcreteComponent extends Component{
@Override
public void operation() {
System.out.println("具体对象的操作");
}
}
Decorator类
abstract class Decorator extends Component{
protected Component component;
public void setComponent(Component component) {
this.component = component;
}
@Override
public void operation() {
// 重写operation(),实际上执行的是Component的operation()
if (component!=null){
component.operation();
}
}
}
ConcreteDecorator 具体实现类
class ConcreteDecoratorA extends Decorator{
//本类的独有功能,以区别于ConcreteDecoratorB
private String addedState;
@Override
public void operation() {
super.operation();
addedState = "New State";
System.out.println("具体装饰对象A的操作");
}
}
class ConcreteDecoratorB extends Decorator{
@Override
public void operation() {
super.operation();
AddBehavior();
System.out.println("具体装饰对象B的操作");
}
//本类的独有方法,以区别于ConcreteDecoratorA
private void AddBehavior(){
}
}
客户端代码
public class DecoratorPattern {
public static void main(String[] args){
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
/*
装饰的方法是:首先用ConcreteComponent实例化对象c,然后用
ConcreteDecoratorA的实例化对象d1来包装c,再用ConcreteDecoratorB
的对象d2包装d1,最终执行d2的operation()
*/
d1.setComponent(c);
d2.setComponent(d1);
d2.operation();
}
}
运行结果
具体对象的操作
具体装饰对象A的操作
具体装饰对象B的操作
示例
例子:之前玩QQ空间的时候,总会装扮空间,打扮形象,可以给qq的角色搭配各种衣服。用程序模拟这个装扮的过程。
UML图:
装饰模式示例UML图.png代码实现:
People类,ConcreteComponent
public class People extends Component{
public People(){}
private String name;
public People(String name) {
this.name = name;
}
@Override
public void operation() {
System.out.println("装饰的是"+name);
}
}
服饰类 Decorator
public class Finery extends People {
protected People component;
//打扮
public void Decorate(People component) {
this.component = component;
}
@Override
public void operation() {
if (component!=null){
component.operation();
}
}
}
具体服饰类-T恤 ConcrteFecorator
public class TShirts extends Finery {
@Override
public void operation() {
System.out.print("TShirts");
super.operation();
}
}
具体服饰类-垮裤 ConcrteFecorator
public class BigTrouser extends Finery {
@Override
public void operation() {
System.out.print("垮裤");
super.operation();
}
}
客户端代码
public class Main {
public static void main(String[] args){
People xiaocheng = new People("小成");
System.out.println("第一种装扮:");
TShirts tShirts = new TShirts();
BigTrouser bigTrouser = new BigTrouser();
tShirts.Decorate(xiaocheng);
bigTrouser.Decorate(tShirts);
bigTrouser.operation();
}
}
运行结果
第一种装扮:
垮裤TShirts装饰的是小成
网友评论