Core Design Patterns(8) Prototype 原型模式

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)  阅读(563)  评论(2编辑  收藏  举报