随笔-42  评论-128  文章-0  trackbacks-4
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) 阅读(195) 评论(2)  编辑 收藏 所属分类: Design Pattern

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-03-14 22:48 编辑过


相关链接: