【设计模式】装饰器模式

参考来源:http://www.runoob.com/design-pattern/decorator-pattern.html

  • 介绍

装饰器模式允许向一个添加新的功能,但是有不改变其结构。这种模式创建一个用于包装原始类的装饰类,在保证原始类方法签名不变的情况下提供新的功能。

  • 作用

  1. 在不想增加很多子类的情况下扩展类;
  2. 作为继承的替代方式,而且类之间不会相互耦合;
  • 实现

在本例中,我们将创建一个Shape接口和实现Shape接口的实体类。然后我们定义抽象装饰类ShapeDecorator,用于所有实现Shape接口的实体类的装饰。

  1. 创建Shape接口
    ​
    public interface Shape {
    	void draw();
    }
    
    ​

     

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

     

  3. 创建用于装饰Shape的抽象装饰类
    public abstract class ShapeDecorator implements Shape{
    	protected Shape decoratedShape;
    	
    	public ShapeDecorator(Shape decoratedShape) {
    		this.decoratedShape = decoratedShape;
    	}
    	
    	public void draw() {//原始类方法签名不变
    		decoratedShape.draw();
    	}
    }
    

     

  4. 创建扩展ShapeDecorator类的实体装饰类
    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");
    	}
    }
    

     

  5. 使用RedShapeDecorator装饰Shape对象
    public class DecoratorPatternDemo {
    	public static void main(String[] args) {
    		Shape circle = new Circle();
    		Shape redCircle = new RedShapeDecorator(new Circle());//装饰Shape对象
    		Shape redRectangle = new RedShapeDecorator(new Rectangle());//装饰Shape对象
    		
    		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();
    	}
    }
    

     

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BQW_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值