建造者模式和享元模式有什么区别?
构建器模式和享元模式在使用方面有什么区别,因为它们都处理大量对象?
What is the difference between Builder Pattern and Flyweight Pattern in terms of usage, as both of them deals with large number of objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Builder 模式用于创建许多对象,而享元模式则用于共享这样的对象集合。
这两种模式都处理“复合”,即可能具有多个元素的对象,但它们根本不需要一起使用。 Flyweight 的原型用例是在文本编辑器应用程序中反复使用几十个字符对象的池(这是 “GoF”书)
The Builder pattern is used to create many objects, whereby the Flyweight pattern is about sharing such a collection of objects.
These two patterns both deal with "composites", i.e. objects that may have several elements, but they don't need to be used together at all. The archetype use case for Flyweight is where a pool of a few dozen characters objects are used over and over in a text editor application (this is the example given in the "GoF" book)
直接来自维基百科。
蝇量级
构建器
一个帮助构建对象,另一个帮助内存使用。您可以使用构建器来“构建”不同的享元对象。
Straight from wikipedia.
Flyweight
Builder
One helps with building objects and the other help with memory usage. You could potentially use a builder to "Build" different flyweight objects.
当“必须操纵许多对象并且这些对象不能承受无关数据”时,享元模式是合适的。在 Java 中,String 对象作为享元进行管理。 Java 将所有固定的字符串文字放入文字池中。对于冗余文字,Java 在池中仅保留一份副本。
使享元发挥作用的关键是使用工厂方法或构建器设计模式控制对象实例化。工厂方法的工作只是创建对象:给定输入条件,返回适当类型的对象。
抽象工厂与构建器类似,它也可以构造复杂的对象。主要区别在于构建器模式侧重于逐步构建复杂的对象。抽象因素的重点是产品对象系列(简单或复杂)。
flyweight pattern is appropriate when "many objects must be manipulated and these cannot afford to have extraneous data." In Java, String objects are managed as flyweight. Java puts all fixed String literals into a literal pool. For redundant literals, Java keeps only one copy in the pool.
The key to making flyweight work is by controlling object instantiation using a factory method or builder design pattern. The job of a factory method is simply to create objects: given input criteria, return an object of appropriate type.
Abstract factory is similar to builder in that it too may construct complex objects. The primary difference is that the Builder pattern focuses on constructing a complex object step by step. Abstract factor's emphasis is on families of product objects(either simple or complex).