I want to have only 5 instance of a class throughout the application life time. How can I achieve this? Please give sample code, if possible.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Look at Object pool pattern. Its java implementation is greatly described in Grand Patterns in Java V1.
Short description from the book overview:
I think you can't. You can force that if somebody want to create or destroy an instance has to use these static methods:
The problem is method destroy. You can't be sure that someone is still referencing the destroyed object.
The Factory pattern could be your friend. One (fictional, not threadsafe and thus quite simple) example to illustrate the approach:
EDIT
The license example was not too good - so I moved it to a domain that expects, that objects created by the factory are not returned and destroyed without noticing the factory. The Bar can't create Martinis when there is no olive left and it definitly doesn't want the drink back after it has been consumed ;-)
EDIT 2 And for sure, only the factory can create Instances (=Drinks). (No guarantee, that the added inner private class fulfills this requirement, don't have an IDE at hand to do a quick test .. feel free to comment or edit)
Have a look at the
static
keyword.You can try following code but written in C#, you can get a basic idea how can it be done.
And mind that this class is't intended to use in multi-threading environment.