23种设计模式

装饰模式:Decorator 常被翻译成"装饰",我觉得翻译成"油漆工"更形象点,油漆工(decorator)是用来刷油漆的,那么被刷油漆的对象我们称 furniture。这两种实体在Decorator 模式中是必须的。

1 Decorator 定义

动态给一个对象添加一些额外的职责,就像在不同家具上刷油漆。使用 Decorator 模式相比用生成子类方式达到功能的扩充显得更为灵活。

2 为什么使用 Decorator?

我们通常可以使用继承来实现功能的拓展,如果这些需要拓展的功能的种类很繁多,那么势必生成很多子类,增加系统的复杂性;同时,使用继承实现功能拓展,我们必须可预见这些拓展功能,这些功能是编译时就确定了,是静态的。
使用 Decorator 的理由是:这些功能需要由用户动态决定加入的方式和时机.Decorator提供了"即插即用"的方法,在运行期间决定何时增加何种功能。

3 如何使用?

举例  小新爱玩游戏;小新可以玩LOL,小新也可以先玩会逆水寒,在玩LOL;小新可以先玩会DNF在玩逆水寒。这些是不定的,可由小新自己灵活确定。

package xx.study.design.decorator;

public interface IPlayGame {
    public void play();
}




package xx.study.design.decorator;

public class PlayLOL implements IPlayGame {
    public void play() {
        System.out.println("我要玩LOL!!!");
    }
}


package xx.study.design.decorator;

import java.util.ArrayList;
import java.util.ListIterator;
//装饰类
public class PlayGameDecorator implements IPlayGame {

    private  IPlayGame iPlayGame;
    //额外的功能打包在list中
    private ArrayList others=new ArrayList();
    public PlayGameDecorator(IPlayGame iPlayGame){
        this.iPlayGame=iPlayGame;
        others.add("我要玩DNF!");
        others.add("我要玩逆水寒!");
    }

    public void play() {

        newMethod();
    }

    /**
     * 添加其他方法,这里的顺序由用户灵活指定
     */
    public void newMethod(){
        otherMethod();
        iPlayGame.play();
    }
    public  void otherMethod(){
        ListIterator listIterator=others.listIterator();
        while (listIterator.hasNext()){
            System.out.println(listIterator.next());
        }
    }
}


package xx.study.design.decorator;

public class PlayGamneDemo {
    public static void main(String[] args) {
        IPlayGame iPlayGame=new PlayLOL();
        IPlayGame decorator=new PlayGameDecorator(iPlayGame);
        decorator.play();
    }
}

 

 

更多推荐