简单工厂 : 和享元模式一样都属于建造类模式,用于创建对象,被建造的所有的实例都有一个共同的父类。和享元模式不同的是:工厂每一个对象都是new出来的,都是不同的对象。而享元模式除了第一次new一个实例对象,其他都是用的此实例对象的缓存,属于同一个对象。
现在,本人以花为例( 可以假设Game中有撒各种花的需求,比如有玩家结婚了满屏撒红花特效 ; 母亲节送礼满屏撒百合花 --- 本人对花的意义的理解不是特别理解,不喜勿喷,只是作为例子来讲解简单工厂模式 ),让我们开始吧 ---
一 , 简单工厂中所有被创建的实例都需要有一个共同的父类 ( 普通类 , 抽象类 , 虚拟类 , 接口 ) , 这篇我以接口为例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleFactory.com
{
/// <summary>
/// 花类的继承接口
/// </summary>
public interface IFlower
{
void Show();
}
}二 ,创建2个子类 : ①RoseFlower(玫瑰) ; ②LilyFlower(百合) , 代码基本一样,我只给出 RoseFlower 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleFactory.com
{
/// <summary>
/// 玫瑰特效
/// </summary>
public sealed class RoseFlower : IFlower
{
public RoseFlower()
{
Console.WriteLine("实例化玫瑰");
}
public void Show()
{
Console.WriteLine("展示玫瑰花特效!");
}
}
}三 , 创建一个工厂类用于生产各种花( 玫瑰 , 百合 ) 重点:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
namespace SimpleFactory.com
{
/// <summary>
/// 花工厂
/// </summary>
public static class FlowersFactory
{
public static IFlower GetFlower( FlowerType flower )
{
switch (flower)
{
case FlowerType.Rose:
return new RoseFlower();
break;
case FlowerType.Lily:
return new LilyFlower();
break;
default:
return null;
break;
}
}
public enum FlowerType : int
{
[Description("玫瑰")]
Rose = 0,
[Description("百合")]
Lily = 1
}
/// <summary>
/// 获取描述信息
/// </summary>
/// <param name="en"></param>
/// <returns></returns>
public static string description(this Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
return en.ToString();
}
}
}其中 GetFlower方法为重点 , 其他为本人扩展 。 在此方法中,根据不同的花( FlowerType )返回不同的实例对象( 多态 )。
测试 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleFactory.com;
namespace SimpleFactory
{
class Program
{
static void Main(string[] args)
{
//获得玫瑰
IFlower rose1 = FlowersFactory.GetFlower(FlowersFactory.FlowerType.Rose);
rose1.Show();
IFlower rose2 = FlowersFactory.GetFlower(FlowersFactory.FlowerType.Rose);
rose2.Show();
Console.Read();
}
}
}结果如下:
本文出自 “Better_Power_Wisdom” 博客,请务必保留此出处http://aonaufly.blog.51cto.com/3554853/1941666
原文地址:http://aonaufly.blog.51cto.com/3554853/1941666