您的位置:首页 > 其它

装饰器模式

2015-09-16 23:08 218 查看

装饰器模式

单一职责原则:就一个类而言,应该仅有一个引起它变化的原因。

核心

把一个类中的核心职责和装饰功能分开,被装饰对象当做参数传入装饰者对象。动态地给一个对象添加一些额外的职责。

好处

装饰类和被装饰类可以独立发展,不会相互耦合,把类中的装饰功能从类中搬除,简化原有的类,去除相关类中的重复装饰的逻辑。

例子

情景:本类是形状,用颜色装饰类装饰。其中,我们将把一个形状装饰上不同的颜色,同时又不改变形状类。

//创建一个接口
public interface Shape{
void draw();
}

//创造实体类Circle实现接口
public class Circle implements Shape {
public void draw(){
System.out.println("Shape: Circle");

4000
}
}

//创建实现接口的实体类Rectangle
public class Rectangle implements Shape {
public void draw(){
System.out.println("Shape: Rectangle");
}
}

//创建实现了 Shape 接口的抽象装饰类。
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;

public ShapeDecorator(Shape decoratedShape){
this.decoratedShape = decoratedShape;
}

public void draw(){
decoratedShape.draw();
}
}

//创建扩展了 ShapeDecorator 类的实体装饰类。
public class RedShapeDecorator extends ShapeDecorator{

public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}

public void draw(){
decoratedShape.draw();
setRedBorder(decoratedShape);
}

private void setRedBorder(Shape decoratedShape) {
System.out.println("Border Color: Red");
}

}

//最后是客户端程序
public class DecoratorPatternDemo {
public static void main(String[] args) {

Shape circle = new Circle();

Shape redCircle = new RedShapeDecorator(new Circle());

Shape redRectangle = new RedShapeDecorator(new Rectangle());
System.out.println("Circle with normal border");
circle.draw();

System.out.println("\nCircle of red border");
redCircle.draw();

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 of red border
Shape: Rectangle
Border Color: Red


例子来源http://www.runoob.com/design-pattern/decorator-pattern.html

源码在我的代码托管上

装饰者模式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: