浅谈C#设计模式之工厂模式
工厂模式和简单工厂有什么区别。废话不多说,对比第一篇例子应该很清楚能看出来。
优点:工厂模式弥补了简单工厂模式中违背开放-封闭原则,又保持了封装对象创建过程的优点。
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceDesignModel
{
publicinterfaceFactory
{
JScreatejs();
}
publicclassJS
{
publicintNumA{get;set;}
publicintNumB{get;set;}
publicvirtualintGetResult()
{
return0;
}
}
publicclassAdd1:JS
{
publicoverrideintGetResult()
{
returnNumA+NumB;
}
}
publicclassSub1:JS
{
publicoverrideintGetResult()
{
returnNumA-NumB;
}
}
publicclassAddFactory:Factory
{
publicJScreatejs()
{
returnnewAdd1();
}
}
publicclassSubFactory:Factory
{
publicJScreatejs()
{
returnnewSub1();
}
}
}
客户端调用:
Factoryfactory=newAddFactory();
JS js=factory.createjs();
js.NumA=1;
js.NumB=2;
Console.WriteLine(js.GetResult());
Factoryf=newSubFactory();
JSJ=f.createjs();
J.NumA=9;
J.NumB=0;
Console.WriteLine(J.GetResult());
Console.ReadLine();
这里主要是对比了下和简单工厂模式的区别,记录下来,以防自己搞混。