最近在很多场合都看见设计模式的影子,一直以来,都投入主要时间在搞算法与数据结构,很来发现设计模式真的很重要。有的时候代码的可维护、可重用、可扩展确实胜过单纯的算法效率高。所以拾起大牛书籍《大话设计模式》同时参考网上诸大牛的博客,开始我的设计模式之旅。
今天先介绍一下装饰模式。
概念:
动态的给某个类添加新的功能。当需要为某个现有的对象动态的增加一个新的功能或职责时,可以考虑使用装饰模式;当然可以通过派生类继承解决上述动态添加功能,但子类膨胀的速度过快,难以控制,往往不可取。
流程:
(1) 抽象构建角色(Component):给出一个抽象的接口,以规范准备接受附加责任的对象。
(2) 具体构建角色(ConcreteComponent):定义一个将要接受附加责任的类。
(3) 装饰角色(Decorator):持有一个抽象构建(Component)角色的引用,并定义一个与抽象构件一致的接口。
(4) 具体装饰角色(ConcreteDecorator):负责给构建对象“贴上”附加的责任。
示例代码
下面是一段关于装饰模式的代码:
package Pattern; /* * 抽象构建角色 */ interface Component { public void DoSomething(); } /* * 具体的构建角色 */ class ConcreteComponent implements Component { public void DoSomething() { System.out.println("完成原有功能"); } } /* * 装饰角色 */ class Decorator implements Component { private Component myComponent; public Decorator(Component tmpComponent) { this.myComponent = tmpComponent; } public void DoSomething() { myComponent.DoSomething(); } } /* * 具体装饰角色 */ class ConcreteDecorator extends Decorator { public ConcreteDecorator(Component tmpComponent) { super(tmpComponent); } private void DoAnotherthing() { System.out.println("完成添加功能"); } public void DoSomething() { super.DoSomething(); DoAnotherthing(); } } public class Pattern { public static void main(String[] args) { try { Component component = new ConcreteDecorator(new ConcreteComponent()); component.DoSomething(); } catch (Exception e) { e.printStackTrace(); } } }
每个人写博客的习惯不一样,上面是我的读书笔记,可能有摘自其他博客http://www.cnblogs.com/hnrainll/archive/2012/03/23/2414180.html的内容,在此表示感谢!