设计模式[6] Decorator Pattern 装饰模式

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

附上UML图:


看了代码就明白了:就是在一个基类外面再包一层。Decorator类的实例重载了基类的方法。把基类的实例包在Decorator里面,然后调用Decorator重载的方法。

看代码:注意那个Decorator.SetComponent() 方法
  //  Decorator pattern -- Structural example

using  System;

namespace  DoFactory.GangOfFour.Decorator.Structural
{

  
// MainApp test application

  
class MainApp
  
{
    
static void Main()
    
{
      
// Create ConcreteComponent and two Decorators
      ConcreteComponent c = new ConcreteComponent();
      ConcreteDecoratorA d1 
= new ConcreteDecoratorA();
      ConcreteDecoratorB d2 
= new ConcreteDecoratorB();

      
// Link decorators
      d1.SetComponent(c);
      d2.SetComponent(d1);

      d2.Operation();

      
// Wait for user
      Console.Read();
    }

  }


  
// "Component"

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


  
// "ConcreteComponent"

  
class ConcreteComponent : Component
  
{
    
public override void Operation()
    
{
      Console.WriteLine(
"ConcreteComponent.Operation()");
    }

  }


  
// "Decorator"

  
abstract class Decorator : Component
  
{
    
protected Component component;

    
public void SetComponent(Component component)
    
{
      
this.component = component;
    }


    
public override void Operation()
    
{
      
if (component != null)
      
{
        component.Operation();
      }

    }

  }


  
// "ConcreteDecoratorA"

  
class ConcreteDecoratorA : Decorator
  
{
    
private string addedState;

    
public override void Operation()
    
{
      
base.Operation();
      addedState 
= "New State";
      Console.WriteLine(
"ConcreteDecoratorA.Operation()");
    }

  }


  
// "ConcreteDecoratorB"

  
class ConcreteDecoratorB : Decorator
  
{
    
public override void Operation()
    
{
      
base.Operation();
      AddedBehavior();
      Console.WriteLine(
"ConcreteDecoratorB.Operation()");
    }


    
void AddedBehavior()
    
{
    }

  }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值