哪种设计模式与工厂模式相反? [英] Which design pattern is the opposite of the Factory pattern?

查看:142
本文介绍了哪种设计模式与工厂模式相反?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道工厂模式是否有相反的模式。例如,当需要删除某个对象时,需要进行额外的工作,以撤消在工厂对象中执行的配置。



扩展工厂对象使用Delete方法例如似乎是错误的,因为工厂模式是严格的创建模式。



更新:我使用工厂的原因是因为配置需要做的是将对对象引入一些不合适的依赖关系。将这个解除配置放在构造函数中会产生同样的问题。

解决方案

这是正确的方法来使用工厂。工厂不仅是创建对象的方法,而且还有一种说法:我需要一个特殊的初始化来处理这些对象。有了你的问题,我认为最好的解决方案是通知工厂,一些事情,如处置。所以您的对象创建将以这样的方式完成:创建,订阅工厂到新创建的对象的事件。每次删除对象时,都会通知工厂,并执行所需的操作。



如果您不想将其放入工厂,可以将其委托给某种其他对象,如DeathKeeper ;-)。所以你的代码将看起来像这样:

  //在工厂内创建方法
MyObject obj = GetNewInitializedObject();
_detahKeeper.RegisterObject(obj);

return obj;

现在每次你都需要删除对象,你的对象将通知死亡管理员,它会使所有处置逻辑。顺便说一下,我不知道它是如何工作的,但是您可以使用IDisposable接口来执行自定义逻辑来处理由对象持有的资源。决定取决于你的项目在哪里,取决于你。


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.

解决方案

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.

这篇关于哪种设计模式与工厂模式相反?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆