davioooh
davioooh

Reputation: 24666

Create different instances of the same class, which design pattern?

I have a custom object ExportType:

public class ExportType{

    protected String name;      
    protected FetchingStrategy fetchStg;
    protected ExportStrategy exportStg;

    public ExportType(String name, FetchingStrategy fetch, ExportStrategy export) {
            this.name = name;
        this.fetchStg = fetch;
        this.exportStg = export;
    }

    // ...
}

In my application I have to create a list of Export types that have different FetchingStrategy and ExportStrategy. New Export types can be created in the future, by implementing new FetchingStrategy and ExportStrategy, so I'd like to design my application to be as flexible as possible.

Is there a design pattern I should apply to obtain what I need? Create a different TypeFactory for each ExportType particular instance is the correct approach?

UPDATE

I try to summarize my problem: I'm working on a web application for the export of data from a db. I have several ways to extract data from DB (ExportTypes), these types are obtained by different combinations of FetchingStrategy and ExportStrategy. Now I need to create a list of these "combinations" to recall them when necessary. I could create constants like:

public static final ExportType TYPE_1 = new ExportType(..., ...);

but I'd like to implement it in a way so I can add in the future new combinations / types.

Upvotes: 2

Views: 825

Answers (3)

Cygnusx1
Cygnusx1

Reputation: 5409

To be as flexible as possible, don't use concrete class. Use Interface.

I would recommend Spring IoC to inject your different implementation of FetchingStrategy and ExportStrategy inside your ExportType.

public class SomeExportType implements IExportType{

    protected String name;
    @Autowired(@Qualifier="SomeFetchingStrategy")      
    protected IFetchingStrategy fetchStg;
    @Autowired(@Qualifier="SomeExportStrategy")      
    protected IExportStrategy exportStg;



    // ...
}

public interface IExportType {
     public void doSomething();  //
}

public interface IFetchingStrategy {
   public void fetch();
}

public class SomeFetchingStrategy implements IFetchingStrategy {

    public void fetch() {
        //implement this strategy
    }

}

Upvotes: 0

mihaisimi
mihaisimi

Reputation: 1999

You can use AbstractFactory: http://en.wikipedia.org/wiki/Abstract_factory_pattern

More details about the way you plan to use these could help.

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35011

Best design pattern for this is to use factories that return interfaces for everything. You can abstract away all implementation then, allowing you to grow and change your system flexibly.

Spring dependency injection is a pretty great solution for this

Your biggest problems are likely to be at the database level, which is harder to abstract

Upvotes: 1

Related Questions