工厂模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了工厂模式相关的知识,希望对你有一定的参考价值。
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();
}
}
}
以上是关于工厂模式的主要内容,如果未能解决你的问题,请参考以下文章
JAVA设计模式——工厂模式简单工厂模式工厂方法模式抽象工厂模式