设计模式--工厂方法,与生活联系
原创
©著作权归作者所有:来自51CTO博客作者wx636b6259489d3的原创作品,请联系作者获取转载授权,否则将追究法律责任
一、个人理解
1、定义创建产品的接口,将实际创建工作延迟到子类中实现
2、实现调用者与具体产品的解耦
3、调用者通过工厂来生成产品
二、生活运用
1、数据库访问控制,支持access,sql,mysql,oracle多种数据库
2、反射工厂模式,利用传入的参数即可找到指定需要的对象
3、旅游公司,选择去游玩的路线即可,无需对产品有具体的了解
三、代码
using System;
using System.Collections.Generic;
using System.Text;
namespace ModeDemo.Factory
{
public abstract class Creator
{
public abstract Product FactoryMethod();
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ModeDemo.Factory
{
public class ConcreateCreator:Creator
{
public override Product FactoryMethod()
{
return new ConcreateProductA();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ModeDemo.Factory
{
public class ConcreateCreatorB:Creator
{
public override Product FactoryMethod()
{
return new ConcreateProductB();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ModeDemo.Factory
{
public abstract class Product
{
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ModeDemo.Factory
{
public class ConcreateProductA:Product
{
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ModeDemo.Factory
{
public class ConcreateProductB:Product
{
}
}
Factory.Creator[] creators = new ModeDemo.Factory.Creator[2];
creators[0] = new Factory.ConcreateCreator();
creators[1] = new Factory.ConcreateCreatorB();
foreach (Factory.Creator creator in creators)
{
Factory.Product product = creator.FactoryMethod();
Console.WriteLine("Created {0}", product.GetType().Name);
}
Console.Read();