












VS 2008
当我们需要实例化一个类的多个实例,并且实例化的代价比较昂贵的时候,可以使用原型模式。
1. 模式UML图

2. 应用

IPrototype.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Prototype.BLL {

public interface IPrototype<T> {

T Clone();
T DeepCopy();
}
}

UserInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace DesignPattern.Prototype.BLL {

[Serializable]
public class UserInfo : IPrototype<UserInfo> {

public int UserId {
get;
set;
}
public string UserName {
get;
set;
}
public PetInfo Pet {
get;
set;
}

IPrototype Members
}
}

PetInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace DesignPattern.Prototype.BLL {

[Serializable]
public class PetInfo {

public string PetName {
get;
set;
}
}
}

Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DesignPattern.Prototype.BLL;

namespace DesignPattern.Prototype {
class Program {
static void Main(string[] args) {
UserInfo u = new UserInfo() {
UserId = 1,
UserName = "guozhijian",
Pet = new PetInfo() {
PetName = "nana"
}
};
UserInfo uCopy = u.Clone();

Console.WriteLine("{0},{1},{2}", uCopy.UserId.ToString(), uCopy.UserName, uCopy.Pet.PetName);

UserInfo uDeepCopy = u.DeepCopy();
uDeepCopy.Pet.PetName = "sasa";
Console.WriteLine("{0},{1},{2}", uDeepCopy.UserId.ToString(), uDeepCopy.UserName, uDeepCopy.Pet.PetName);

Console.WriteLine(u.Pet.PetName);


}
}
}

Output

posted on 2008-03-14 21:48 Tristan(GuoZhijian) 阅读(595) 评论() 收藏 举报
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。