DesignPattern-Simple Factory

简单工厂模式:专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。它又称为静态工厂方法模式。它的实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类(这些产品类继承自一个父类或接口)的实例。简单工厂模式的创建目标,所有创建的对象都是充当这个角色的某个具体类的实例。在这个模式中,工厂类是整个模式的关键所在。它包含必要的判断逻辑,能够根据外界给定的信息,决定究竟应该创建哪个具体类的对象。用户在使用时可以直接根据工厂类去创建所需的实例,而无需了解这些对象是如何创建以及如何组织的。有利于整个软件体系结构的优化。


接口

public interface 动物

{

void 跑();

}

实现

public class 狮子

{

public void 跑()

{

-------

}

}

public class 老虎

{

public void 跑()

{

---------

}

}

。。。。。


工厂

public class 动物园

{

public static 动物 狮子()

{

return new 狮子();

}

public static 动物 老虎()

{

return new 老虎();

}

----------

}


2011.09.09 重新思考

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

namespace Design_Patterns
{
    //接口 集合父类
    interface Car
    {
        void Run();
    }

    public class BMW : Car
    {
        #region Car 成员

        public void Run()
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    public class Audi : Car
    {
        #region Car 成员

        public void Run()
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    public class Bentley : Car
    {
        #region Car 成员

        public void Run()
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    public class Benz : Car
    {
        #region Car 成员

        public void Run()
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    public enum CarType{BMW,Audi,Bentley,Benz};
    //简单工厂 静态工厂方法 负责所有类型对象的创建,不支持无缝的新增新的类型对象的创建。(产品的种类是“不变”的,只是想隐藏产品的实例化过程和具体的产品)

    //简单的项目使用
    class SimpleFactory
    {
        public static Car GetCar(CarType ctype)
        {
            Car car = null;
            switch (ctype)
            {
                case CarType.BMW:
                    car = new BMW();
                    break;
                case CarType.Audi:
                    car = new Audi();
                    break;
                case CarType.Bentley:
                    car = new Bentley();
                    break;
                case CarType.Benz:
                    car = new Benz();
                    break;
                default:
                    break;
            }
            return car;
        }
    }
    //调用
    class Test
    {
        Car c = SimpleFactory.GetCar(CarType.BMW);
        public Test()
        {
            c.Run();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值