1. 程式人生 > >C#/.NET 反射(配置檔案)實現簡單工廠

C#/.NET 反射(配置檔案)實現簡單工廠

C# 反射(配置檔案)實現簡單工廠

配置檔案

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
    <requiredRuntime version="v4.0.20506"/>
  </startup>
  <appSettings>
    <add key="AbstractShape" 
         value="WSX.DXF,
         WSX.DXF.Models.Analyse.LineDetails,
         WSX.DXF.Models.Analyse.CircleDetails,
         WSX.DXF.Models.Analyse.ArcDetails,
         WSX.DXF.Models.Analyse.PLineDetails"/>
  </appSettings>
</configuration>

public enum ShapeTypes
{
	Point,
	Line,
	Circle,
	Arc,
	PLine
}

public class ApplicationParameters
{
	protected static string ShapeDLL = ConfigurationManager.AppSettings["AbstractShape"];
	protected static string DllName = ShapeDLL.Split(',')[0];
	protected static string LineTypeName = ShapeDLL.Split(',')[1];
	protected static string CircleTypeName = ShapeDLL.Split(',')[2];
	protected static string ArcTypeName = ShapeDLL.Split(',')[3];
	protected static string PLineTypeName = ShapeDLL.Split(',')[4];
}

public class ObjectFactory : ApplicationParameters
{
	public static AbstractDetailsBase CreatShape(ShapeTypes shape)
	{
		Type type = null;
		Assembly assembly = Assembly.Load(DllName);
		switch (shape)
		{
			case ShapeTypes.Line:
				type = assembly.GetType(LineTypeName);
				break;
			case ShapeTypes.Circle:
				type = assembly.GetType(CircleTypeName);
				break;
			case ShapeTypes.Arc:
				type = assembly.GetType(ArcTypeName);
				break;
			case ShapeTypes.PLine:
				type = assembly.GetType(PLineTypeName);
				break;
		}
		AbstractDetailsBase aShape = Activator.CreateInstance(type) as AbstractDetailsBase;
		return aShape;
	}
}


實現呼叫

var details = ObjectFactory.CreatShape(ShapeTypes.PLine);