Structural Patterns Part 4/7: Decorator Pattern

Structural Patterns Part 4/7: Decorator Pattern

目录


Definition

Decorator Pattern是对一个已有对象的再封装,可以说实现了一个Wrapper的功能。它会在已有对象的基础上添加更多的功能而不会改变已有对象的结构(通过组合来实现),通常Decorator和其封装的对象是来自同一个类或接口的。

一个现实中的例子就是JavaEE中的DAO实体,对应的是数据库中的表记录,一般设计好了就不会再改变,所以很多情况下都会对这个实体进行再封装。

何时使用?当希望在现有对象的基础上添加新的功能而又不想改变其结构时。

使用频率:Frequency of use Medium


UML Class Diagram

Decorator Pattern


Implementation

现在有个Pad,它本身可以玩游戏,现在对它进行装饰一下,从而可以通过键鼠或者是手柄来玩它上面的游戏。

// Pad.java
package designpatternsstructuralpatterns.decorator;

public interface Pad {
    void playGames();
}

// PadImpl.java
package designpatternsstructuralpatterns.decorator;

class iPad implements Pad {

    @Override
    public void playGames() {
        System.out.println("Playing Games on an iPad.");
    }
}

// DecoratorDemo.java
package designpatternsstructuralpatterns.decorator;

public class DecoratorDemo {
    public static void main(String[] args) {
        Pad iPad = new iPad();
        Decorator kmDecorator = new KeyboardMouseDecorator(iPad);
        kmDecorator.playGames();

        System.out.println("=========================");

        Decorator jsDecorator = new JoyStickDecorator(kmDecorator);
        jsDecorator.playGames();
    }
}

abstract class Decorator implements Pad {

    protected Pad decoratedPad;

    public Decorator(Pad decoratedPad) {
        this.decoratedPad = decoratedPad;
    }

    public abstract void playGames();

    protected abstract void playWithOuterDevice();  
}

class KeyboardMouseDecorator extends Decorator {

    public KeyboardMouseDecorator(Pad decoratedPad) {
        super(decoratedPad);
    }

    @Override
    public void playGames() {
        decoratedPad.playGames();
        playWithOuterDevice();
    }

    @Override
    protected void playWithOuterDevice() {
        System.out.println("With a keyboard and a mouse!!!");
    }
}

class JoyStickDecorator extends Decorator {

    public JoyStickDecorator(Pad decoratedPad) {
        super(decoratedPad);
    }

    @Override
    public void playGames() {
        decoratedPad.playGames();
        playWithOuterDevice();
    }

    @Override
    protected void playWithOuterDevice() {
        System.out.println("With a joy stick!!!");
    }   
}

// output
Playing Games on an iPad.
With a keyboard and a mouse!!!
=========================
Playing Games on an iPad.
With a keyboard and a mouse!!!
With a joy stick!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值