介绍意图:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更灵活。
主要解决:我们扩展一个类常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会越来越膨胀。
如何使用:在不想增加很多子类的情况下扩展。
如何解决:将具体功能职责划分,同时继承装饰者模式。
关键代码:
1. component 类充当抽象角色,不应该具体实现。
2. 修饰类引用合继承 component 类,具体扩展类重写父类方法。
使用场景:
1. 扩展一个类的功能。
2. 动态增加功能,动态撤销。
实现创建一个 shape 接口合实现了 shape 接口的实体类。然后再创建一个实现了 shape 接口的抽象装饰类 shapedecorator,并把 shape 对象作为它的实例变量。redshapedecorator 是实现了 shapedecorator 的实体类。decoratorpatterndemo 类使用 redshapedecorator 来装饰 shape 对象。
步骤1:
public interface shape{ void draw();}
步骤2:
public class rectangle implements shape{ @override public ovid draw(){ system.out.println("draw rectangle"); }}
public class cricle implements shape{ @override public ovid draw(){ system.out.println("draw circle"); }}
步骤3:
public abstract class shapedecorator implements shape{ private shape shape; // 持有一个 shape 对象 public shapedecorator(shape shape){ this.shape = shape; } public void draw(){ shape.draw();// todo 根据传进来的具体 shape 对象,调用对应的 draw 方法 }}
步骤4:
public class redshapedecorator extends shapedecorator{ public redshapedecorator(shape shape){ super(shape); } @override public void draw(){ shape.draw(); setredborder(shape); } public void setredborder(shape shape){ system.out.println("border color: red"); }}
步骤5
public class decoratorpatternddemo{ public static void main(string args[]){ //todo 面向抽象层编程 // 普通的circle shape circle = new circle(); system.out.println("circle with normal border"); circle.darw(); // 红色边界的 circle shapedecorator redcircle = new redshapedecorator(new circle); system.out.println("circle of red border"); redcircle.draw(); // 红色边界的 rectangle shapedecorator redrectangle = new redshapedecorator(new rectangel): system.out.println("rectangle of red border"); redrectangle.draw(); }}
优缺点优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
缺点:多层装饰比较复杂。
以上就是java结构型设计模式之装饰模式怎么实现的详细内容。