首页 > 代码库 > 工厂模式

工厂模式

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

/*

工厂模式

*/


namespace App_MYCS.HDL_SJMS.GCMS
{
class my_GCMS_DY
{
public void GCMS_DY()
{
IFactory f = new IF_GCMS_zl_1();
GCMS_Fl clms = f.gcms_function();
clms.A1 = 1;
clms.A2 = 3;
int a = clms.appfunction();
}
}


//对外只有工厂类
public class my_GCMS
{
//工厂类生成返回对象
public static GCMS_Fl GetObj(string objstr)
{
try
{
GCMS_Fl cfl = null;
switch (objstr)
{
case "+":
cfl = new class_GCMS_zl_1();
break;
case "-":
cfl = new class_GCMS_zl_2();
break;
default:
break;
}
return cfl;
}
catch (Exception)
{
return null;
}
}
}


/// <summary>
/// 运算类
/// </summary>
public class GCMS_Fl
{

//抽取同类的几个类的公共属性
//和公共方法(同类方法)
private int a1;

public int A1
{
get { return a1; }
set { a1 = value; }
}
private int a2;

public int A2
{
get { return a2; }
set { a2 = value; }
}

public virtual int appfunction()
{
return A1 + A2;
}

}
/// <summary>
/// 各个子类
/// </summary>
public class class_GCMS_zl_1 : GCMS_Fl
{
public override int appfunction()
{
return A1 + A2;
}
}

public class class_GCMS_zl_2 : GCMS_Fl
{
public override int appfunction()
{
return A1 - A2;
}

}


/// <summary>
/// 工厂接口
/// </summary>
interface IFactory
{
GCMS_Fl gcms_function();
}
/// <summary>
/// 子工厂
/// </summary>
class IF_GCMS_zl_1 : IFactory
{
public GCMS_Fl gcms_function()
{
return new class_GCMS_zl_1();
}
}

class IF_GCMS_zl_2 : IFactory
{
public GCMS_Fl gcms_function()
{
return new class_GCMS_zl_2();
}
}


}

工厂模式