Skip to content
Advertisement

How do you use anonymous objects with the factory pattern?

I have a method as so:

public class FooFactory {
    public Foo createNewFoo(){
        return new foo();
    }
}

Now if I do this:

FooFactory fooFactory = new FooFactory();
Foo foo = FooFactory.createNewFoo();

It’ll work perfectly fine. However, if I try to do this :

new Foo() = FooFactory.createNewFoo();

It doesn’t seem to work at all. It says “variable expected”.

I understand that new Foo() in itself, creates a new Foo object, but even if I use the factory, it should just override the anonymous object with a new Foo object.

I’ve also tried creating an ArrayList that holds Foo’s and doing

arrayList.add(new Foo());
arrayList.get(0) = FooFactory.createNewFoo();

It still says “variable expected”. Why is it saying that?

Foo foo = new Foo();
Foo otherFoo = foo;

This works perfectly fine, so I don’t understand why I can’t make the factory work with an anonymous object.

I tried searching for this online, but I got no search results, which tells me that I’m probably making some ridiculous mistake/using the factory pattern wrong.

Advertisement

Answer

Equals is an assignment operator.

targetOfMyAssignment = thingImAssigning;

new Foo() is statement that creates an object. It is a producer. You can’t assign anything to it, it’s not a variable reference. Variable references, like Foo foo =, are consumers. arraylist.get(0) is also a producer. that statement, just like a constructor, provides a value, but it is not a reference for you to assign something to. arraylist.add(object) is also a consumer.


I think you also misunderstand what an anonymous type is; an anonymous type is one where you override some or all of it’s behavior in-line, by specifying the new behavior after the class declaration with {}. For example:

Runnable r = new Runnable() {
  public void run() {
    // code
  }
};

You need an anonymous type because Runnable is an interface, there’s no behavior defined for run(), so Runnable r = new Runnable(); won’t compile.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement