只有5个类的实例
我希望在整个应用程序生命周期中只有5个类的实例。 我怎样才能做到这一点? 如果可能,请提供示例代码。
由于单身人士应使用枚举(参见“有效Java”):
public enum FiveInstance { INSTANCE1, INSTANCE2, INSTANCE3, INSTANCE4, INSTANCE5; public void anyMethod() {} }
格雷茨GHad
工厂模式可能是你的朋友。 一个(虚构的,不是线程安全的,因此非常简单)的例子来说明这种方法:
public static MartiniFactory { private static int olives = 100; // you asked for '5' but 100 is more realistic // for this example. public static Drink createMartini() throws OutOfOlivesException { if (olives > 0) { olives--; return new Martini(new Gin(4), new Vermouth(1), new Olive()); else { throw new OutOfOlivesException(); } } // forgot to mention, only the factory (=bar) is able to create Martinis, so: private class Martini { Martini(Ingredient... ingredients) { // ... } // .... } }
编辑
许可证示例并不太好 – 所以我将其移动到了一个域,该域期望工厂创建的对象不会在不注意工厂的情况下返回和销毁。 当没有剩下的橄榄时,酒吧不能创造马提尼酒,并且它确实不希望饮料在消费后回来;-)
编辑2当然,只有工厂可以创建实例(=饮料)。 (无法保证,增加的内部私有类符合此要求,手头没有IDE可以进行快速测试..随意评论或编辑)
看看static
关键字。
class Sample { private static int i = 0; private Sample() { } public static Sample CreateInstance() { if(i <5) { i++; return new Sample(); } else throw new Exception("Can not create more then 5 instance of this class"); } }
public class FiveInstance { private static int instanceCount = 0; private FiveInstance(){ } public static FiveInstance getNewInstance() throws InstanceExceededException{ if(instanceCount < 5){ instanceCount++; return new FiveInstance(); }else{ throw new InstanceExceededException(); } } }
创建一个私有static
成员来计算class
的实例。 然后,确保您的类的每个构造函数都增加此static
变量并测试溢出。 如果你有多个构造函数,我建议你让一个构造函数实现这个行为,其他人应该调用它。 尝试创建第六个实例时构造函数的行为取决于您。 也许你想抛出Exception
。
您可以尝试使用以下代码但使用C#编写,您可以基本了解如何完成。
public class MultiTone { private static MultiTone _cache; private static int _counter=5; MultiTone() { } public static MultiTone GetInstance() { if(_counter==0) { return _cache ?? (_cache = new MultiTone()); } _counter--; return new MultiTone(); } }
并且请注意,此类不适用于multithreading环境。
我想你不能。 您可以强制,如果有人想要创建或销毁实例必须使用这些静态方法:
import java.util.*; public class Fiveton { public final static int MAX_INSTANCES = 5; private static List instances = new ArrayList (); private Fiveton() { } public static Fiveton getInstance() { if (instances.size()>=MAX_INSTANCES) throw new RuntimeException("Hey! You've reached the maximum of instances: " + MAX_INSTANCES); Fiveton instance = new Fiveton(); instances.add(instance); return instance; } public static void destroy(Fiveton instance) { instances.remove(instance); } }
问题是方法破坏。 您无法确定某人是否仍在引用已销毁的对象。
作为Singleton的扩展,有一种称为Multiton的模式可以解决这个问题。 似乎没有人很清楚这是一种独立的模式或者是Singleton的变体。 查看链接,它包含示例代码。
查看对象池模式 。 它的Java实现在Java V1中的Grand Patterns中有很大的描述。
书中概述的简短描述:
对象池
管理对象类型的重用,这些对象的创建成本很高,或者只能创建有限数量的对象。
创建一个名为howMany
的静态字段,每次调用构造函数时都会增加该字段。
当howMany
=> 5时,拒绝创建对象。