Which design pattern is the opposite of the Factory pattern?

六月ゝ 毕业季﹏ 提交于 2019-12-10 12:44:10

问题


I was wondering if there is an opposite pattern of the factory pattern. For example, when a certain object needs to be deleted some extra work needs to be done, to undo the configuration which was performed in the factory object.

Extending the factory object with a Delete method for instance seems wrong, since the factory pattern is a strict creational pattern.

Update: The reason why I'm using a factory is because the configuration which needs to be done would introduce some dependencies to the object which wouldn't fit. Putting this de-configuration in the constructor would pose the same problem.


回答1:


That's right way to use factory. Factory is not only way to create objects, but also the way to say: I need a special initialization for these kind of objects. With your problem I think the best solution would be to notify factory with some event, like disposed. So your object creation will be done in such a way: create, subscribe factory to event of newly created object. Every time object is deleted you`ll notify factory on that and perform action you need.

If you don't like to put this into factory, you can delegate it to some kind of other object, like DeathKeeper ;-). So your code will look sometihng like this:

//Inside factory create method
MyObject obj = GetNewInitializedObject();
_detahKeeper.RegisterObject(obj);

return obj;

Now every time you will need to delete object, your object will notify death keeper and it would make all dispose logic. By the way, I do not know how it all works, but you can use IDisposable interface to do the custom logic for disposing resources held by object. The decision depends on what`s there in your project and is up to you.




回答2:


A repository could be used to delete a persisted object, or you could use the dispose method to do some cleanup on an in memory only object.




回答3:


I use a "Recycling Facility" pattern working in tandem with the Factory:

  • have a "clean" method for each class that can be recycled
  • have a "unique id" for each object instance

Each time an object reaches its end-of-life, send it to the "Recycling Facility" (RF):

  • The RF stores the object according to some policy ( e.g. keep only X instances of class Y )
  • When a an instance of class Y is required, the Factory "asks" the RF if its got one
    • if the RF has one handy, the RF calls the "clean()" method on the instance and returns it to the Factory

... and so on so forth.

Hope this helps.



来源:https://stackoverflow.com/questions/1425755/which-design-pattern-is-the-opposite-of-the-factory-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!