java设计模式——结构型模式专题(一)装饰模式

来源:互联网 发布:linux远程ssh登录失败 编辑:程序博客网 时间:2024/05/17 10:27

概念

装饰模式:说白了就是动态扩展对象



UML:


上代码:


抽象构件(Component)角色:将核心方法抽象出来的接口。

package 装饰模式;public interface Component {public abstract void Operition();}


具体构件(ConcreteComponent)角色:实现了接口的核心功能的类。
package 装饰模式;public class ConcreteComponent implements Component {    @Overridepublic void Operition(){    System.out.println("this is ConcreteComponent");    }}


装饰(Decorator)角色:持有一个构件(Component)对象的实例并定义一个与抽象构件接口一致的接口(方法)。
package 装饰模式;public class Decorator implements Component {Component comp = null;public Decorator(Component comp) {this.comp = comp;}@Overridepublic void Operition() {// TODO 自动生成的方法存根        comp.Operition();}}


具体装饰(ConcreteDecorator)角色负责修饰ConcreteComponent

package 装饰模式;public class ConcreteDecoratorA extends Decorator {public ConcreteDecoratorA(Component comp) {super(comp);}@Overridepublic void Operition() {System.out.println("this is ConcreteDecoratorA");super.Operition();}     }
package 装饰模式;public class ConcreteDecoratorB extends Decorator {public ConcreteDecoratorB(Component comp) {super(comp);}@Overridepublic void Operition() {System.out.println("this is ConcreteDecoratorB");super.Operition();}  }

测试代码:(相关的看法在代码中有阐述)

package 装饰模式;public class Main {/** * @param args */public static void main(String[] args) {// TODO 自动生成的方法存根          Component comp = new ConcreteComponent();//持有核心代码的具体实现类        ConcreteDecoratorA decA = new ConcreteDecoratorA(comp);//在保留核心代码的前提下,扩展功能(即“装饰”新功能)        ConcreteDecoratorB decB = new ConcreteDecoratorB(comp);                    //结果://        this is ConcreteDecoratorA//        this is ConcreteComponent////        this is ConcreteDecoratorB//        this is ConcreteComponent                //------------------------------------------------------        //        ConcreteDecoratorA decA = new ConcreteDecoratorA(comp);//        ConcreteDecoratorB decB = new ConcreteDecoratorB(decA);//实现功能的叠加                //------------------------------------------------------                //设想一下:如果我们不用装饰模式,那么在已有核心功能A前提下,我需要添加功能B,则一般想法是“多重继承”,再         //创建一个子类去继承具有核心功能的类,从而组合的功能是A+B,此时,我如果再想扩展功能C,那么就继续去创建一个类        //继承拥有B功能的类,注意哦,现在是2重继承了。        //如果,我现在要扩展功能D,但又不需要功能B怎么办,或者不需要功能C又怎么办?...完全凌乱了        //如果用装饰模式,那么我会很方便的实现A+B,A+C,A+D,或者A+B+D,A+C+D等组合。                                decA.Operition();        System.out.println();        decB.Operition();                        //结果://        this is ConcreteDecoratorA//        this is ConcreteComponent////        this is ConcreteDecoratorB//        this is ConcreteDecoratorA//        this is ConcreteComponent        }}

装饰模式优点:

1,转移了主类装饰功能,简化主类,或者说避免了多重继承的复杂度。

2,把类的核心职责和修饰功能区分开,而且可以去除相关类中重复的修饰逻辑。




0 0
原创粉丝点击