C#设计模式之建造者(Builder)模式示例源代码
2024-07-21 02:25:29
供稿:网友
using system;
using system.collections;
//product
public class computer
{
private string type;
private hashtable info=new hashtable ();
public computer(string type)
{
type=type;
console .writeline ("conputer "+type+" is builded!");
}
public string this[string key]
{
get
{
return (string)info[key];
}
set
{
info[key]=value;
}
}
public void show()
{
console .writeline ("this is a computer of "+type+" :");
console .writeline (" "+info["cpu"]);
console .writeline (" "+info["ram"]);
}
}
//builder
public abstract class builder
{
protected computer computer;
public computer computpter
{
get
{
return computer;
}
}
public builder(string type)
{
computer=new computer (type);
}
abstract public void buildcpu();
abstract public void builderram();
}
public class macbuilder:builder
{
public macbuilder(string type):base(type)
{}
public override void buildcpu()
{
computer["cpu"]="maccpu";
}
public override void builderram()
{
computer["ram"]="maccpu";
}
}
public class pcbuilder:builder
{
public pcbuilder(string type):base(type)
{}
public override void buildcpu()
{
computer["cpu"]="pccpu";
}
public override void builderram()
{
computer["ram"]="pccpu";
}
}
public class worker
{
public void construct(builder builder)
{
builder.buildcpu();
builder.builderram();
}
}
public class ceo
{
public static void main()
{
try
{
worker worker=new worker ();
builder pcbuilder=new pcbuilder ("pc");
builder macbuilder=new macbuilder ("mac");
worker .construct(pcbuilder);
worker.construct(macbuilder);
pcbuilder.computpter.show ();
macbuilder.computpter.show ();
}
catch(exception ex)
{
console.writeline ("error:"+ex.source+" "+ex.innerexception+ex.stacktrace+ex.targetsite);
}
}
}