设计模式(一)——工厂模式、策略模式
设计模式(二)——工厂模式进阶:工厂方法模式、抽象工厂模式
之前的两篇文章中学习了简单工厂模式、策略模式、工厂方法模式以及抽象工厂模式,但是这几种设计模式有一个共同特点,都属于创建型模式,创建都是有共同的接口指向创建的对象。通俗的来讲,它们都是用来处理同类型的业务逻辑。如果需要向现有的结构添加不同的新的功能,同时保证不改变其原有的结构,这就需要用到结构型模式
装饰模式
装饰器模式,动态的给一个对象添加一些额外的职责。就新增功能来说,装饰器模式相比子类更为灵活。主要解决通过继承的方式实现对一个类的扩展,随着扩展功能的增多,子类会很膨胀的问题。在不想增加很多子类的情况下扩展类就可以采用装饰模式来设计。下面以换装为例,用装饰模式来设计实现:
public class Person
{
private string name;
public Person(string name)
{
this.name = name;
}
public Person()
{
}
public virtual void Show()
{
Console.WriteLine("装扮的{0}", this.name);
}
}
/// <summary>
/// 服饰基类
/// </summary>
public class Finery : Person
{
protected Person component;
public void Decorate(Person component)
{
this.component = component;
}
public override void Show()
{
if (component != null)
{
component.Show();
}
}
}
/// <summary>
/// 垮裤
/// </summary>
public class BigTrouser : Finery
{
public override void Show()
{
Console.Write("垮裤 ");
base.Show();
}
}
...类似代码不重复赘述
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Person person = new Person("张三");
Sneakers dec_1 = new Sneakers();
BigTrouser dec_2 = new BigTrouser();
TShirts dec_3 = new TShirts();
///装饰过程
dec_1.Decorate(person);
dec_2.Decorate(dec_1);
dec_3.Decorate(dec_2);
dec_3.Show();
}
}
利用装饰器模式,可以便捷的位Person组装不同类型的功能模块,就此例而言,新增其它服饰类别时,只需要继承基类服饰Finery 即可,可以很方便的扩展内容。