创建型模式-简单工厂模式

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

namespace 简单工厂模式
{

   

    public class SimpleFactory
    {
    
        //将此函数改为静态的则变为了静态工厂方法
        public IProduct CreateProduct(string productName)
        {
            switch (productName)
            {
                case "ProductA":
                    return new ProductA();
                case "ProdcutB":
                    return new ProductB();
                default:
                    throw new Exception("创建产品错误!");

            }
        }
    }

    public interface IProduct
    {
        void MustDoSomething();
    }

    public class ProductA : IProduct
    {
        public ProductA()
        { }
        public void MustDoSomething()
        {
            //产品A的业务逻辑
        }
    }

    public class ProductB : IProduct
    {
        public ProductB()
        {
 
        }
        public void MustDoSomething()
        {
            //产品B的业务逻辑
        }
    }

    public class AppClient
    {
        public static void Main(string[] args)
        {
            SimpleFactory afactory = new SimpleFactory();
            IProduct  producta = afactory.CreateProduct("ProductA");
            producta.MustDoSomething();//调用产品A的方法
            IProduct productb = afactory.CreateProduct("ProdcutB");
            productb.MustDoSomething();//将调用产品B的方法
        }
        
        
       
    }

   
}
posted @ 2011-03-04 22:56  日月之明  阅读(333)  评论(0编辑  收藏  举报