我正在做一个多平台的事情,但我对 OOP 不是很好。目前我的代码是:
public interface IMessageBox {
void Show(string Text);
void Show(string Text, string Description, MessageBoxType Type);
MessageBoxResult ShowYesNo(string Text, string Description, MessageBoxType Type);
MessageBoxResult ShowYesNoCancel(string Text, string Description, MessageBoxType Type);
}
public class MessageBox : InstanceGenerator {
public static void Show(string Text) {
MessageBoxImpl.Show(Text);
}
public static void Show(string Text, string Description, MessageBoxType Type) {
MessageBoxImpl.Show(Text, Description, Type);
}
public static MessageBoxResult ShowYesNo(string Text, string Description, MessageBoxType Type) {
return MessageBoxImpl.ShowYesNo(Text, Description, Type);
}
public static MessageBoxResult ShowYesNoCancel(string Text, string Description, MessageBoxType Type) {
return MessageBoxImpl.ShowYesNoCancel(Text, Description, Type);
}
}
protected class InstanceGenerator {
public static IMessageBox MessageBoxImpl = null;
public static IWindow WindowImpl = null;
private static Assembly Instance = null;
private static string InstanceName = null;
private static Assembly LoadAssembly(string lib) {
string AppPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Assembly assembly = Assembly.LoadFile(Path.Combine(AppPath, lib + ".dll"));
return assembly;
}
private static object CreateInstance(string @class) {
Type type = Instance.GetType(InstanceName + "." + @class);
return Activator.CreateInstance(type);
}
private static object CreateInstanceFromPath(string lib, string @class) {
string AppPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Assembly assembly = Assembly.LoadFile(Path.Combine(AppPath, lib + ".dll"));
Type type = assembly.GetType(lib + "." + @class);
return Activator.CreateInstance(type);
}
/// <summary>
/// Inits the whole thing
/// </summary>
public static void Init() {
if (CurrentOS.IsWindows)
InstanceName = "Lib.Windows";
else if (CurrentOS.IsMac)
InstanceName = "Lib.MacOS";
else if (CurrentOS.IsLinux)
InstanceName = "Lib.Linux";
else // no implementation for other OSes
throw new Exception("No implementation of Lib for this OS");
Instance = LoadAssembly(InstanceName);
// initialize the classes
MessageBoxImpl = (IMessageBox) CreateInstance("MessageBox");
}
}
编辑:
其中 InstanceGenerator 返回从程序集加载的 IMessageBox 的实例。有没有更好的方法来创建/连接到实例?实现所有相同的静态方法看起来根本不是一个好的解决方案。有没有更自动的方法来用类包装这些接口,或者我做错了什么?