随笔-42  评论-128  文章-0  trackbacks-4
VS 2008

工厂方法模式提供创建一系列属于同一产品体系的类的创建方法。并且,有别于一般的简单工厂,工厂方法模式创建产品由子类来完成。这样增加新的产品不需要修改原来的代码,只需要相应增加一个新的工厂子类。

1. 模式UML图



2. 应用

    程序中需要使用到不同的交通工具,将交通工具的行为抽象为一个接口,那么这些交通工具就形成了一个有共同行为的产品体系。根据工厂方法模式的思想,为产品的创建相应的建立一套工厂体系。



ITransportation.cs

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

namespace DesignPattern.FactoryMethod.BLL {

    
public interface ITransportation {

        
void Run();
    }

}


Car.cs

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

namespace DesignPattern.FactoryMethod.BLL {

    
public class Car : ITransportation {
        
ITransportation Members
    }

}


Plane.cs

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

namespace DesignPattern.FactoryMethod.BLL {

    
public class Plane : ITransportation {
        
ITransportation Members
    }

}


ITransportationFactory.cs

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

namespace DesignPattern.FactoryMethod.BLL {
    
public interface ITransportationFactory {

        ITransportation Create();
    }

}


CarFactory.cs

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

namespace DesignPattern.FactoryMethod.BLL {

    
public class CarFactory : ITransportationFactory {
        
ITransportationFactory Members
    }

}


PlaneFactory.cs

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

namespace DesignPattern.FactoryMethod.BLL {

    
public class PlaneFactory : ITransportationFactory {
        
ITransportationFactory Members
    }

}


Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DesignPattern.FactoryMethod.BLL;

namespace DesignPattern.FactoryMethod {
    
class Program {
        
static void Main(string[] args) {

            ITransportationFactory carFactory 
= new CarFactory();
            ITransportation car 
= carFactory.Create();
            car.Run();

            ITransportationFactory planeFactory 
= new PlaneFactory();
            ITransportation plane 
= planeFactory.Create();
            plane.Run();
        }

    }

}


Output

posted on 2008-03-14 22:48 Tristan(GuoZhijian) 阅读(252) 评论(3)  编辑 收藏 所属分类: Design Pattern

评论:
#1楼  2008-03-19 20:57 | beniao [未注册用户]
学习过,做个记号.
  回复  引用    
#2楼  2008-08-03 22:59 | 维维糖 [未注册用户]
我的QQ号379858431
想加你~~
想弄清楚最新的抽象工厂是怎么弄的
  回复  引用    

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      


相关链接: