Fork me on GitHub

设计模式-创建型模式-抽象工厂模式

抽象工厂模式

 抽象工厂模式是对简单工厂模式的封装

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleFactory
{
    public class Operation
    {
        public double NumberA { get; set; }
        public double NumberB { get; set; }

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

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

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

    public class OperationMultiplication : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA * NumberB;
            return result;
        }
    }

    public class OperationDivision : Operation
    {
        public override double GetResult()
        {
            if(NumberB==0)
            {
                throw new Exception("除数不能为0!!!记住啦");
            }
            else
            {
                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;
                case "*":
                    oper=new OperationMultiplication();
                    break;
                case "/":
                    oper = new OperationDivision();
                    break;
            }
            return oper;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入第一个数字:");
            double numberA = double.Parse(Console.ReadLine());
            Console.WriteLine("请输入操作符:");
            string opera = Console.ReadLine();
            Console.WriteLine("请输入第二个数字");
            double numberB=double.Parse(Console.ReadLine());
            Operation oper = new Operation();
            oper = OperationFactory.CreateOperate(opera);
            oper.NumberA = numberA;
            oper.NumberB = numberB;
            double result = oper.GetResult();
            Console.WriteLine(result.ToString());
            Console.ReadKey();
        }
    }
}

 

posted @ 2013-10-30 20:55  种花生的读书人  阅读(195)  评论(0编辑  收藏  举报

该博客仅作为记录笔记,转载随意