Pluge模式,是最常见的模式,实现后期绑定。增加程序灵活性,通过配制文件可以方便配制不同的实现。
这篇POST以简单方式实现,代码中细节就不说了。
接口:
实现:
客户类:
这里使用的是appSettings,实际中还可以用自定义配制节。
Ps:我们还可以用Asp.net中的Provider模式,IOC来实现。
这篇POST以简单方式实现,代码中细节就不说了。
接口:
namespace SamplePlugePattern.Interface
{
/// <summary>
/// define a action interface
/// </summary>
public interface IAction
{
void Burn();
}
}
{
/// <summary>
/// define a action interface
/// </summary>
public interface IAction
{
void Burn();
}
}
实现:
namespace Machine
{
public class MachineT50:IAction
{
public void Burn()
{
Console.WriteLine("MachineT50 is burning now.");
}
}
}
{
public class MachineT50:IAction
{
public void Burn()
{
Console.WriteLine("MachineT50 is burning now.");
}
}
}
客户类:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Configuration;
using SamplePlugePattern.Interface;
namespace WorkPlat
{
/// <summary>
/// Pluge Pattern Sample
/// </summary>
/// <remarks>author PetterLiu http://wintersun.cnblogs.com </remarks>
class Program
{
static void Main(string[] args)
{
string AssemblyName = ConfigurationManager.AppSettings["AssemblyName"];
string TypeName = ConfigurationManager.AppSettings["TypeName"];
IAction action = UsingActivator(AssemblyName, TypeName);
action.Burn();
}
private static IAction UsingCurrentAppDomain(string assemblyname, string typename)
{
return AppDomain.CurrentDomain.CreateInstanceAndUnwrap(assemblyname, typename) as IAction;
}
private static IAction UsingActivator(string assemblyname, string typename)
{
Assembly assembly = Assembly.Load(assemblyname);
Type type = assembly.GetType(typename);
return Activator.CreateInstance(type) as IAction;
}
}
}
using System.Collections.Generic;
using System.Reflection;
using System.Configuration;
using SamplePlugePattern.Interface;
namespace WorkPlat
{
/// <summary>
/// Pluge Pattern Sample
/// </summary>
/// <remarks>author PetterLiu http://wintersun.cnblogs.com </remarks>
class Program
{
static void Main(string[] args)
{
string AssemblyName = ConfigurationManager.AppSettings["AssemblyName"];
string TypeName = ConfigurationManager.AppSettings["TypeName"];
IAction action = UsingActivator(AssemblyName, TypeName);
action.Burn();
}
private static IAction UsingCurrentAppDomain(string assemblyname, string typename)
{
return AppDomain.CurrentDomain.CreateInstanceAndUnwrap(assemblyname, typename) as IAction;
}
private static IAction UsingActivator(string assemblyname, string typename)
{
Assembly assembly = Assembly.Load(assemblyname);
Type type = assembly.GetType(typename);
return Activator.CreateInstance(type) as IAction;
}
}
}
这里使用的是appSettings,实际中还可以用自定义配制节。
<configuration>
<appSettings>
<add key="AssemblyName" value="Machine"/>
<add key="TypeName" value="Machine.MachineT50"/>
</appSettings>
</configuration>
<appSettings>
<add key="AssemblyName" value="Machine"/>
<add key="TypeName" value="Machine.MachineT50"/>
</appSettings>
</configuration>
Ps:我们还可以用Asp.net中的Provider模式,IOC来实现。