zoukankan      html  css  js  c++  java
  • 浅尝DesignPattern_Decorator

    UML:

    Component:定义一个对象接口,可以给这些对象动态的添加职责

    ContreteComponent:定义了一个具体的对象,也可以给这个对象添加一些职责

    Decorator:装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decrator的存在的

    ContreteDecoratorA和ContreteDecoratorB都是具体的装饰对象,骑到给Component添加职责的功能

    SAMPLE:

    Component.cs

    abstract class Component
    {
    public abstract void Operation();
    }

    ConcreteComponent.cs

    1 class ConcreteComponent:Component
    2 {
    3 public override void Operation()
    4 {
    5 Console.WriteLine("具体对象的操作");
    6 }
    7 }
    Decorator.cs
    1 abstract class Decorator:Component
    2 {
    3 protected Component component;
    4 public void setComponent(Component component)
    5 {
    6 this.component = component;
    7 }
    8 public override void Operation()
    9 {
    10 if (component != null)
    11 component.Operation();
    12 }
    13 }
    ConcreteDecoratorA.cs
    1 class ConcreteDecoratorA : Decorator
    2 {
    3 private string addedState;
    4 public override void Operation()
    5 {
    6 base.Operation();
    7 addedState = "new state";
    8 Console.WriteLine("具体装饰对象A的操作");
    9 }
    10 }
    ConcreteDecoratorB.cs
    1 class ConcreteDecoratorB:Decorator
    2 {
    3 public override void Operation()
    4 {
    5 base.Operation();
    6 addMethod();
    7 Console.WriteLine("具体装饰对象B的操作");
    8 }
    9 //用来区别A方法
    10 private void addMethod()
    11 { }
    12 }
    Program.cs
    1 ConcreteComponent c = new ConcreteComponent();
    2 ConcreteDecoratorA d1 = new ConcreteDecoratorA();
    3 ConcreteDecoratorB d2 = new ConcreteDecoratorB();
    4
    5 d1.setComponent(c);
    6 d2.setComponent(d2);
    7 d2.Operation();
    装饰模式是利用setComponent来对付对象进行包装的.这样每个装饰独享的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中.
  • 相关阅读:
    2013上半年中国CRM市场分析报告
    windows运行命令大全
    JVM探索(二)
    JVM探索(一)
    1.数据结构和算法的基础笔记
    java程序性能优化
    http状态码
    mongodb清洗数据
    List的数据结构
    Foundation Data Structure
  • 原文地址:https://www.cnblogs.com/TivonStone/p/1718258.html
Copyright © 2011-2022 走看看