关于装饰器:设计模式之装饰器模式

4次阅读

共计 2485 个字符,预计需要花费 7 分钟才能阅读完成。

基本概念

装璜器模式,顾名思义起的是装璜的作用,就是在一个类上减少性能。如果通过继承来减少性能,在不批改代码的状况下,如果减少性能多的话,会使类的数量爆炸式增长,为治理带来微小的麻烦。装璜器模式就比拟好地解决了这一点。

介绍

以下为装璜器模式的通用类图: 

  • Component,个别是接口或者抽象类,定义了最简略的办法,装璜器类和被装璜类都要实现该接口。
  • ConcreteComponent,被装璜类,实现了 Component。
  • Decorator,装璜器类,通过该类为 ConcreteComponent 动静增加额定的办法,实现了 Component 接口,并且该对象中持有一个 Component 的成员变量。
  • ConcreteDecoratorA,ConcreteDecoratorB,具体的装璜类,该类中的办法就是要为 ConcreteComponent 动静增加的办法。

实现

咱们以生产一件衣服为例,生产一件衣服自身是个很简略的过程,一块布料裁剪好了之后做出衣服的样子就能够了,然而这样的衣服是卖不出去的,因为毫无美感,咱们须要通过一些装璜来使衣服变得难看。然而时代在变动,人们的审美也在变动,装璜总是一直在变的,所以咱们就要有一个灵活机动的模式来批改装璜。

Clothes.java

public interface Clothes {public void makeClothes(); } 

MakeClothes.java

public class MakeClothes implements Clothes {@Override     public void makeClothes() {System.out.println("制作一件衣服");     }  } 
  1. 步骤 3 创立装璜器。

OperationSubstract.java

public class OperationSubstract implements Strategy{@Override    public int doOperation(int num1, int num2) {return num1 - num2;} } 

话不多说,先来个衣服的最后成品,就是毫无美感的那种,那么如果当初要减少装璜,能够用一个类继承 MakeClothes,而后减少外面 makeClothes() 办法,然而如果过几天装璜就变了,那么又要改变代码,而且如果装璜过多,这个类就显得很庞杂,不好保护,这个时候装璜器模式就来大显神通了。

Decorator.java

public class Decorator implements Clothes {private Clothes clothes;     public Decorator(Clothes _clothes) {this.clothes = _clothes;}     @Override     public void makeClothes() {         clothes.makeClothes();     } } 

这就是一个装璜器,它有一个构造函数,参数是一个衣服类,同时它重写了 makeClothes() 办法,以便它的子类对其进行批改。上面是两个子类,别离对衣服进行了绣花和镂空

Embroidery.java

public class Embroidery extends Decorator {public Embroidery(Clothes _clothes) {super(_clothes);     }     public void embroidery() {         System.out.println("给衣服绣花");     }     @Override     public void makeClothes() {         super.makeClothes();         this.embroidery();} } 

Hollow.java

public class Hollow extends Decorator {public Hollow(Clothes _clothes) {super(_clothes);     }     public void hollow() {         System.out.println("要害地位镂空");     }     @Override     public void makeClothes() {         super.makeClothes();         this.hollow();} } 

这两个子类的结构器都传入一个衣服模型,而且两个子类别离有各自的办法——绣花和镂空,然而他们均重写了 makeClothes() 办法,在制作衣服的过程中退出了绣花和镂空的操作,这样一来,咱们只须要增删改这几个装璜器的子类,就能够实现各种不同的装璜,简洁明了,高深莫测。上面测试一下:

DecoratorDemo.java

public class DecoratorDemo {public static void main(String[] args) {Clothes clothes = new MakeClothes();         clothes = new Embroidery(clothes);         clothes = new Hollow(clothes);         clothes.makeClothes();         System.out.println("衣服做好了");     } } 

执行程序,输入后果:

 制作一件衣服 给衣服绣花 要害地位镂空 衣服做好了 
正文完
 0