09@设计模式—(07)装饰模式

来源:互联网 发布:手机写码软件 编辑:程序博客网 时间:2024/05/29 17:14

装饰模式(Decorator Pattern)在不修改原有对象内部数据结构的情况下往里面添加新的功能。它是结构型模式中的一种,实际上就是用已经存在的类来创建一个包装类。

这种设计模式创建一个装饰类,这个装饰类将包装原有的类,并为它提供附加的功能,同时原有类的方法的签名不变(就是方法名和方法参数都不变,同时返回数据类型也不变)。

具体实现
我们将创建一个Shape接口,然后创建一些实现类来实现这个Shape接口。接着我们创建一个抽象(abstract)类ShapeDecorator去实现Shape接口。同时抽象类中有一个类型为Shape的属性,这个属性作为这个接口的具体实现。新建RedShapeDecorator作为ShapeDecorator的子类。最后创建DecoratorPatternDemo类,我们将在这个类中使用RedShapeDecorator来装饰类型对象。
装饰模式类图

第一步:创建一个Shape接口

Shape.java

package com.pattern.decorator;public interface Shape {    void draw();}

第二步:创建实现类(Rectangle和Circle)实现Shape接口

Rectangle.java

package com.pattern.decorator;public class Rectangle implements Shape{    @Override    public void draw() {        System.out.println("Shape: Rectangle");    }}

Circle.java

package com.pattern.decorator;public class Circle implements Shape{    public void draw() {        System.out.println("Shape: Circle");    }}

第三步:创建抽象的装饰类实现Shape接口

ShapeDecorator.java

package com.pattern.decorator;public abstract class ShapeDecorator implements Shape{    protected Shape decoratedShape;    public ShapeDecorator(Shape decoratedShape)    {        this.decoratedShape = decoratedShape;    }    public void draw() {        this.decoratedShape.draw();    }}

第四步:创建实现类(RedShapeDecorator)继承ShapeDecorator类

RedShapeDecorator.java

package com.pattern.decorator;public class RedShapeDecorator extends ShapeDecorator{    public RedShapeDecorator(Shape decoratedShape) {        super(decoratedShape);    }    @Override    public void draw()    {      decoratedShape.draw();                 setRedBorder(decoratedShape);    }    private void setRedBorder(Shape decoratedShape)    {        System.out.println("Border Color: Red");    }}

第五步:使用RedShapeDecorator来装饰Shape objects

DecoratorPatternDemo.java

package com.pattern.decorator;public class DecoratorPatternDemo {    public static void main(String args[]){        Shape circle =new Circle();        System.out.println("Circle with normal border");        circle.draw();        Shape redCircle =new RedShapeDecorator(new Circle());        System.out.println("\nCircle of red border");        redCircle.draw();        Shape rectangle = new Rectangle();        System.out.println("\nRectangle with normal border");        rectangle.draw();        Shape redRectangle =new RedShapeDecorator(new Rectangle());        System.out.println("\nRectangle of red border");        redRectangle.draw();    }}

第六步:验证输出

Circle with normal borderShape: CircleCircle of red borderShape: CircleBorder Color: RedRectangle with normal borderShape: RectangleRectangle of red borderShape: RectangleBorder Color: Red
0 0
原创粉丝点击