1.简单工厂模式

 

定义:类型属于创建型模式,又叫静态工厂方法模式。是由一个工厂对象决定创建出哪一种产品的实例。是工厂模式的特例。

优点:工厂类,根据外界给定的信息,决定究竟应该创建那个具体类的对象。调用时候不必管这些对象究竟如何创建和组织,明确了各自的职责和权利,有利于整体软件体系结构的优化。

缺点:由于工厂类集中了所有实例的创建逻辑,违反了高内聚责任分配原则,将全部创建逻辑集中到一个工厂类中;如果需要添加新的类,则需要更改工厂类了。

因此一般只是很简单的情况下应用。

实例:简单计算器,运算工厂类OperationFactory,Operation运算父类,OperationAdd加法子类……,

 

Operation运算父类:

    public class Operation
    {
        private double numA;

        public double NumA
        {
            get { return numA; }
            set { numA = value; }
        }
        private double numB;

        public double NumB
        {
            get { return numB; }
            set { numB = value; }
        }

        public virtual double GetResult()
        {
            double result = 0;
            return result;
        }

    }

 

    public class OperationAdd:Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumA + NumB;
            return result;
        }
    }

    public class OperationSub : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumA - NumB;
            return result;
        }
    }


    public class OperationMul : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumA * NumB;
            return result;
        }
    }


    public class OperationDiv : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            if (NumB==0)
            {
                throw new Exception("除数不能为零!");
            }
            result = NumA / NumB;
            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;

                case "*":
                    oper = new OperationMul();
                    break;

                case "/":
                    oper = new OperationDiv();
                    break;


            }
            return oper;
        }
    }


页面端调用:

            Operation oper;
            oper= OperationFactory.createOperate("/");

            oper.NumA = 1;
            oper.NumB = 3;
            Label1.Text=oper.GetResult().ToString();

 

 

posted @ 2012-07-02 13:46  Xyang  阅读(133)  评论(0编辑  收藏  举报
hi