Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use an interface or factory (and interface) for a cross-platform implementation?

Example A:

// pseudo code
interface IFoo {
    void bar();
}

class FooPlatformA : IFoo {
    void bar() { /* ... */ }
}

class FooPlatformB : IFoo {
    void bar() { /* ... */ }
}

class Foo : IFoo {
    IFoo m_foo;
    public Foo() {
        if (detectPlatformA()} {
            m_foo = new FooPlatformA();
        } else {
            m_foo = new FooPlatformB();
        }
    }

    // wrapper function - downside is we'd have to create one 
    // of these for each function, which doesn't seem right.
    void bar() {
        m_foo.bar();
    }
}

Main() {
    Foo foo = new Foo();
    foo.bar();
}

Example B:

// pseudo code
interface IFoo {
    void bar();
}

class FooPlatformA : IFoo {
    void bar() { /* ... */ }
}

class FooPlatformB : IFoo {
    void bar() { /* ... */ }
}

class FooFactory {
    IFoo newFoo() {
        if (detectPlatformA()} {
            return new FooPlatformA();
        } else {
            return new FooPlatformB();
        }
    }
}

Main() {
    FooFactory factory = new FooFactory();
    IFoo foo = factory.newFoo();
    foo.bar();
}

Which is the better option, example A, B, neither, or "it depends"?

like image 897
Nick Bolton Avatar asked Jun 08 '10 14:06

Nick Bolton


People also ask

When would you use the GoF Factory Method design pattern?

Factory method lets a class defer instantiation to subclass. Factory needs an object (whose concrete class is not known or whose concrete class may change as per the different application type ) to perform a task.

What problem does factory pattern solve?

The factory pattern aims to solve a fundamental problem in instantiation – i.e., the creation of a concrete object of a class – in object-oriented programming. In principle, creating an object directly within the class that needs or should use this object is possible, but very inflexible.

What is the difference between Factory Method and abstract factory?

Factory: A factory that creates objects that derive from a particular base class. Abstract factory: A factory that creates other factories, and these factories in turn create objects derived from base classes.


1 Answers

I would say that your explicit factory option (option B) is generally better.

In your first example your Foo class is effectively doing two jobs, it's a factory and it's a proxy. Two jobs, one class, makes me uneasy.

Your second option puts a little more responsibility on the client: they need to know to use the factory, but this is such a widely used idiom that I think it's not hard to understand.

like image 119
djna Avatar answered Sep 24 '22 06:09

djna