苦逼也聊模式--(1)--简单工厂

既然要提及工厂模式就需要提及一下简单工厂。

简单工厂模式: 是类的创建模式,也可以称为静态工厂。

可以这么理解。

工厂可以生产一个类别的产品,产品必须归属于类别。就如飞机属于飞行器和鸡蛋不是同一类的一样。

现在以飞行器为例子

 

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Aircraft a = AircraftFactory.create(1);
            a.Fly();
            a.Inventor();
        }
    }


    public interface Aircraft
    {
         void Fly();//飞行器的特征,要会飞
         void Inventor();//发明人,可能有品牌什么的就不写了
    }

    public class Airplane : Aircraft
    {
        public void Fly()
        {
            Console.WriteLine("我在天空飞翔");
        }
        public void Inventor()
        {
            Console.WriteLine("地球人");
        }
    }
    public class UFO : Aircraft
    {
        public void Fly()
        {
            Console.WriteLine("我在太空飞翔");
        }
        public void Inventor()
        {
            Console.WriteLine("外星人");
        }
    }

    public class AircraftFactory
    {
        public static Aircraft create(int what)
        {
            if (what == 1)
                return new Airplane();
            else if (what == 2)
                return new UFO();
            else
                return null;
        }
    }
}

  举个例子:计算器的加减乘除可以用这个模式

posted @ 2016-01-13 09:10  root_u  阅读(261)  评论(0编辑  收藏  举报