1

要应用享元模式,我们需要将对象属性分为内在属性和外在属性。内在属性使对象独一无二,而外在属性由客户端代码设置并用于执行不同的操作。

但我的问题是,为什么我们不能同时拥有内在和外在属性作为实例变量(参见下面的电子邮件类),只在循环外创建一个对象并在循环中设置参数并发送多封具有不同参数的电子邮件。

public class Test {
    public static void main(String[] args) {
        Email ob = new Email();
        for (int i = 0; i < 10; i++) {
            ob.sender = String.valueOf(i);
            ob.sendEmail();
        }
    }
}

public class Email {
    public String sender;
    public void sendEmail()
    {
        System.out.println("Email sent to sender:"+sender);
    }
}
4

2 回答 2

5

Sometimes, patterns are not obvious but it doesn't mean they are useless. And I'm afraid you understood the flyweight pattern incorrectly.

The main idea is to minimize memory use by sharing same objects which have already been used before. Usually, there is a data structure internally which is responsible for keeping values and returning them by some criteria. It looks up already existing element rather than creating a new one.

Actually, it is useful. For example, JDK uses this pattern to provide the Integer cache (keeps a small range of values to give them back effectively) and the String pool (look at the intern() method).

于 2016-10-02T14:40:15.610 回答
0

Flyweight告诉我们的只是“处理不可变对象的方式”

  • 如果某些类型的对象是不可变的(我通常更喜欢所有对象尽可能不可变),
  • 你在应用程序中创建了一个对象,带有一些属性,例如:一个不可变 Person对象是用name = "John", age = 20
  • name = "John", age = 20在应用程序执行( )一段时间后,你有另一个完全一样的对象,
  • 只需使用之前创建的,无需创建另一个(无需担心,因为它是不可变的,之后属性不会改变)

所以它基本上是一种节省内存的工作。它与面向对象无关。

于 2016-10-05T03:07:30.520 回答