static void Main(string[] args)
{
Simple simpleOne = new SimpleOne();
simpleOne.ShowName();
Simple simpleTwo = new SimpleTwo();
simpleTwo.ShowName();
// 创建对象
Simple simple1 = Factory.CreateIntance(SimpleType.SimpleOne);
Simple simple2 = Factory.CreateIntance(SimpleType.SimpleTwo);
// 反射工厂
Simple reflectionRe = ReflectionReFactory.CreateIntance();
using System;
using System.Collections.Generic;
using System.Text;
namespace _Net初级
{
public enum SimpleType
{
SimpleOne = 0,
SimpleTwo = 2,
}
/// <summary>
/// 简单工厂
/// </summary>
public class Factory
{
public static Simple CreateIntance(SimpleType simpleType)
{
// 这个 地方可放在配置文件,根据配置去生成所想要的对象
string config = "可以从配置文件读取";
var type = Enum.TryParse(config, out SimpleType simple);
switch (simpleType)
{
case SimpleType.SimpleOne:
return new SimpleOne();
case SimpleType.SimpleTwo:
return new SimpleTwo();
default:
throw new Exception(" Error");
}
}
}
/// <summary>
/// 反射工厂
/// </summary>
public class ReflectionReFactory
{
public static Simple CreateIntance()
{
//ObjectHandle是远程MarshalByRefObject的, 由远程处理生存期服务跟踪。 如果的ObjectHandle生存期租约过期, 则对当前方法的调用可能会失败。
return (Simple)Activator.CreateInstance($"程序集名称", "类型名称").Unwrap();
}
}
public abstract class Simple
{
public abstract void ShowName();
/// <summary>
/// 抽象类可以有自己的方法,接口不能有实现
/// </summary>
public void GetName()
{
}
}
public class SimpleOne : Simple
{
public override void ShowName()
{
Console.WriteLine($"{nameof(SimpleOne)}_{nameof(ShowName)}");
}
}
public class SimpleTwo : Simple
{
public override void ShowName()
{
Console.WriteLine($"{nameof(SimpleTwo)}_{nameof(ShowName)}");
}
}
}