设计模式之-简单工厂
在简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。缺点是违背了“开放-封闭”原则。
示例代码
public class Operation { private double _numberA = 0; private double _numberB = 0; public double NumberA { get; set; } public double NumberB { get; set; } public virtual double GetResult() { double result = 0; return result; } } class OperationAdd:Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } class OperationSub : Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } //简单工厂模式,到底实例化谁,将来会不会增加实例化的对象 public class OperationFactory { public static Operation createOperate(string operate) { Operation oper = null; switch(operate) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; } return oper; } } static void Main(string[] args) { Operation oper; oper = OperationFactory.createOperate("+"); oper.NumberA = 1; oper.NumberB = 2; double result = oper.GetResult(); Console.WriteLine(result); }
UML类图:
#include<iostream> #include<string> using namespace std; class Person { protected: string sex; public: virtual void SetSex() { } virtual string GetSex() { return sex; } }; class Man :public Person { public: void SetSex() { sex = "Man"; } string GetSex() { return sex; } }; class Woman :public Person { public: void SetSex() { sex = "Woman"; } string GetSex() { return sex; } }; class SampleFactory { public: static Person* Produce(char type) { switch (type) { case'W': { return(new Woman()); break; } case'M': { return(new Man()); break; } } } }; int main() { Person* p0 = SampleFactory::Produce('W'); p0->SetSex(); string result0 = p0->GetSex(); cout << result0 << endl; Person *p1 = SampleFactory::Produce('M'); p1->SetSex(); string result1 = p1->GetSex(); cout << result1 << endl; return 0; }