multiton

C++ templated class implementation of the multiton pattern

拥有回忆 提交于 2020-12-29 07:53:50
问题 I implemented the multiton pattern using a templated class in C++. #ifndef MULTITON_H #define MULTITON_H #include <map> template <typename Key, typename T> class Multiton { public: static void destroy() { for (typename std::map<Key, T*>::iterator it = instances.begin(); it != instances.end(); ++it) { delete (*it).second; } } static T& getRef(const Key& key) { typename std::map<Key, T*>::iterator it = instances.find(key); if (it != instances.end()) { return *(T*)(it->second); } T* instance =

How to create a class that doesn't re-create an object with identical input parameters

心已入冬 提交于 2020-01-04 08:26:11
问题 I am trying to create a class that doesn't re-create an object with the same input parameters. When I try to instantiate a class with the same parameters that were used to create an already-existing object, I just want my new class to return a pointer to the already-created (expensively-created) object. This is what I have tried so far: class myobject0(object): # At first, I didn't realize that even already-instantiated # objects had their __init__ called again instances = {} def __new__(cls

Thread-safe multiton pattern

久未见 提交于 2019-12-22 12:44:18
问题 Inspired by a comment to an given answer I tried to create a thread-safe implementation of the multiton pattern, which relies on unique keys and performs locks on them (I have the idea from JB Nizet 's answer on this question). Question Is the implementation I provided viable? I'm not interested in whether Multiton (or Singleton) are in general good patterns, it would result in a discussion. I just want a clean and working implementation. Contras : You have to know how many instances you want

WeakMultiton: ensuring there's only one object for a specific database row

大憨熊 提交于 2019-12-11 10:36:37
问题 In my application I need to ensure that for an entity representing a data row in a database I have at most one java object representing it. Ensuring that they are equals() is not enough, since I could get caught by coherency problems. So basically I need a multiton; moreover, I need not to keep this object in memory when it is not necessary, so I will be using weak references. I have devised this solution: package com.example; public class DbEntity { // a DbEntity holds a strong reference to

Thread safe multitons in Java

淺唱寂寞╮ 提交于 2019-11-26 03:36:32
问题 Given the following multiton: public class Multiton { private static final Multiton[] instances = new Multiton[...]; private Multiton(...) { //... } public static Multiton getInstance(int which) { if(instances[which] == null) { instances[which] = new Multiton(...); } return instances[which]; } } How can we keep it thread safe and lazy without the expensive synchronization of the getInstance() method and the controversy of double-checked locking? An effective way for singletons is mentioned