简单工厂模式

工厂模式分三种:简单工厂模式,工厂方法模式,抽象工厂模式。

今天看了下简单工厂模式。记得之前看《大话设计模式》时候,举例用的是面向对象的简单加减乘除计算器的设计,跟这个差不太多。就想着写写简单的代码,记录下自己学习的历程。其实,看的书很多很乱很杂,而且前面看了,后面就忘记了,最多也只是有个印象而已,现在开始多敲敲示例代码吧。仅仅是做个笔记而已,高手勿喷~~TKS~~

简单工厂模式,直接贴代码。

 

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

namespace SimpleFactory
{
    class Program
    {
        static void Main(string[] args)
        {        
            ShapeFactory sf = new ShapeFactory();
            IShape shape = sf.GetShape("Circle");
            shape.Draw();
            shape.Erase();
            Console.WriteLine("--------------------------------------------");


            shape = sf.GetShape("Rectangular");
            shape.Draw();
            shape.Erase();
            Console.WriteLine("--------------------------------------------");


            shape = sf.GetShape("Triangle");
            shape.Draw();
            shape.Erase();        
            Console.ReadKey();
        }
    }

    class ShapeFactory
    {
        public IShape GetShape(string shapeType)
        {
            IShape shape;
            switch (shapeType)
            {
                case "Circle":
                    shape = new Circle();
                    break;
                case "Rectangular":
                    shape = new Rectangular();
                    break;
                case "Triangle":
                    shape = new Triangle();
                    break;
                default:
                    shape = null;
                    break;
            }
            return shape;
        }
    }

    interface  IShape
    {
          void Draw();//画
          void Erase();//擦除
    }

    /// <summary>
    /// 圆形具体产品类
    /// </summary>
    class Circle : IShape
    {
        public void Draw()
        {
            Console.WriteLine("画圆形!");
        }

        public void Erase()
        {
            Console.WriteLine("擦除圆形!");
        }
    }

    /// <summary>
    /// 矩形具体产品类
    /// </summary>
    class Rectangular : IShape
    {
        public void Draw()
        {
            Console.WriteLine("画矩形!");
        }

        public void Erase()
        {
            Console.WriteLine("擦除矩形!");
        }
    }

    /// <summary>
    /// 矩形具体产品类
    /// </summary>
    class Triangle : IShape
    {
        public void Draw()
        {
            Console.WriteLine("画三角形!");
        }

        public void Erase()
        {
            Console.WriteLine("擦除三角形!");
        }
    }
}

posted @ 2013-04-05 01:03  冲锋撞大树  阅读(175)  评论(1)    收藏  举报