昨晚事情实在太多,没来得及更新。今天要学习的是装饰者模式(Deocorator Pattern).
装饰者模式定义:装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
装饰模式包含如下角色:
1.Component (抽象构件)
2.ConcreteComponent(具体构件)
3.Decorator(抽象装饰类)
4.ConcreteDecorator(具体装饰类)
类图
装饰模式特点(引自百度百科)
实例:
某系统提供了一个数据加密功能,可以对字符串进行加密。最 简单的加密算法通过对字母进行移位来实现,同时还提供了稍 复杂的逆向输出加密,还提供了更为高级的求模加密。用户先 使用最简单的加密算法对字符串进行加密,如果觉得还不够可 以对加密之后的结果使用其他加密算法进行二次加密,当然也 可以进行第三次加密。现使用装饰模式设计该多重加密系统。
类图:
抽象构建类 Cipher
public abstract class Cipher
{
public abstract string encrypt(String plainText);
}
具体构件类 SimpherCilpher
public class SimpleCipher : Cipher
{
public override string encrypt(String plainText)
{
String str = "";
for (int i = 0; i < plainText.Length; i++)
{
char c = plainText[i];
if (c >= 'a' && c <= 'z')
{
c += (char)6;
if (c > 'z') c -= (char)26;
if(c<'a') c += (char)26;
}
if (c >= 'A' && c <= 'Z')
{
c += (char)6;
if (c > 'Z') c -= (char)26;
if(c<'A') c += (char)26;
}
str += c;
}
return str;
}
}
抽象装饰类 CipherDecorator
class CipherDecorator : Cipher
{
private Cipher cipher;
public CipherDecorator(Cipher cipher)
{
this.cipher = cipher;
}
public override String encrypt(String plainText)
{
return cipher.encrypt(plainText);
}
}
具体装饰类 ComplexCipher
class ComplexCipher : CipherDecorator
{
public ComplexCipher(Cipher cipher):base(cipher)
{
}
public override string encrypt(string plainText)
{
String result= base.encrypt(plainText);
result = reverse(result);
return result;
}
private string reverse(string text)
{
String str = "";
for(int i=text.Length;i>0;i--)
{
str += text.Substring(i-1,1);
}
return str;
}
}
具体装饰类 AdvancedCipher
class AdvancedCipher :CipherDecorator
{
public AdvancedCipher(Cipher cipher): base(cipher)
{
}
public override string encrypt(string plainText)
{
string result =base.encrypt(plainText);
result=mod(result);
return result;
}
public string mod(string text)
{
string str = "";
for (int i = 0; i < text.Length; i++)
{
string c = ((int)text[i] % 6).ToString();
str += c;
}
return str;
}
}
Program.cs
class Program
{
static void Main(string[] args)
{
string pawd = "sunnyLiu";
string cpasword;
Cipher pw,cpw,apw;
pw = new SimpleCipher();
cpasword = pw.encrypt(pawd);
Console.WriteLine(cpasword);
cpw = new ComplexCipher(pw);
cpasword = cpw.encrypt(pawd);
Console.WriteLine(cpasword);
apw = new AdvancedCipher(cpw);
cpasword = apw.encrypt(pawd);
Console.WriteLine(cpasword);
Console.ReadKey();
}
}
优点:
装饰这模式和继承的目的都是扩展对象的功能,但装饰者模式比继承更灵活,并且有很好地可扩展性
通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合
缺点:
装饰者模式会导致设计中出现许多小对象,如果过度使用,会让程序变的更复杂。并且更多的对象会是的差错变得困难,特别是这些对象看上去都很像。
使用场景:
需要扩展一个类的功能或给一个类增加附加责任。
需要动态地给一个对象增加功能,这些功能可以再动态地撤销。
需要增加由一些基本功能的排列组合而产生的非常大量的功能
感觉始终理解不是很深,忘得也快,这该怎么办啊~~~~~1