兄Die,写代码太累了?孤独寂寞冷?还没有女朋友吧?
关注微信公众号(瓠悠笑软件部落),送知识!送知识!送温暖!送工作!送女朋友!插科打诨哟!

装饰模式(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 border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle with normal border
Shape: Rectangle
Rectangle of red border
Shape: Rectangle
Border Color: Red

本文详细介绍了装饰模式的概念及其在Java中的具体实现过程。装饰模式是一种结构型设计模式,可以在不改变原有对象的基础上为其添加新的功能。文章通过创建Shape接口及其实现类,再利用抽象装饰类ShapeDecorator和具体的RedShapeDecorator类进行装饰,展示了如何为不同形状添加红色边框。

被折叠的 条评论
为什么被折叠?



