我有一个工厂。我不想让这个工厂生产的类在工厂之外被实例化。如果我让它们抽象、静态或给它们私有构造函数,那么它们根本就不能实例化!这是语言限制还是什么?
我不想让这个
var awcrap = new Extrude2013 (); // BAD !!!
awcrap.extrudify (); // I don't want to allow this
其余代码:
using System;
namespace testie
{
public enum ExtrudeType { Extrude2013, Extrude2014 }
public interface IExtrudeStuff {
void extrudify();
}
public class Extrude2013 : IExtrudeStuff {
public void extrudify(){
Console.WriteLine ("extrudify 2013");
}
}
public class Extrude2014 : IExtrudeStuff {
public void extrudify(){
Console.WriteLine ("extrudify 2014");
}
}
public static class ExtrudeFactory {
public static IExtrudeStuff Create(ExtrudeType t) {
switch (t) {
case ExtrudeType.Extrude2013: return new Extrude2013 ();
case ExtrudeType.Extrude2014: return new Extrude2014 ();
default: return null;
}
}
}
class MainClass {
public static void Main (string[] args) {
// Now for the pretty API part
var o = ExtrudeFactory.Create (ExtrudeType.Extrude2013);
o.extrudify ();
var p = ExtrudeFactory.Create (ExtrudeType.Extrude2014);
p.extrudify ();
var awcrap = new Extrude2013 (); // BAD !!!
awcrap.extrudify (); // I don't want to allow this
}
}
}