hey, hi i want put limit on object creation means a class can have at most suppose 4 objects not more than that how to achieve this?
相关问题
- how to define constructor for Python's new Nam
- Keeping track of variable instances
- Object.create() bug?
- std::vector of objects / pointers / smart pointers
- Name for a method that has only side effects
相关文章
- 接口B继承接口A,但是又不添加新的方法。这样有什么意义吗?
- NameError: name 'self' is not defined, eve
- Implementation Strategies for Object Orientation
- Check if the Type of an Object is inherited from a
- When to use Interfaces in PHP
- Are default parameters bad practice in OOP?
- How to return new instance of subclass while initi
- Builders in Java versus C++?
One way to achieve is the Singleton Design pattern, Whenever we make a call to create an instance, check the count of the instance which are already created, if the instance count is already reached 4, then use the same instance for your application. TO have a count, Creat Static Int Counter = 0; and keep incrementing it to get the results.
Try modifying the Singleton pattern. You can use a count variable. You'll need to keep the Constructor private to have control over the no. of instances.
The simplest way to do this would be to have a class level attribute called "count", and in your constructor, just make sure that "count" isn't above a certain number.
This is short code snippest that will give the above result in c#
One approach is using an object factory that creates at most 4 instances. It's an interesting need... Would an object pool serve the same need?
You can count the numbers of instances created by using a static class property to store the count. This can either be done in the class constructor or you can make use of a factory pattern. It is a bit difficult to answer this more precisely without knowing the target language.