简体   繁体   中英

Strategy pattern to create objects?

Is it a good practice to pass a strategy instance (an interface implementation) to a method so that the method can return objects of a specific type based on the strategy instance type?

For example,

I have a method getData(String x, String y) but this needs to return objects of either type A or type B . Most of the stuff in this method is common and hence i'm thinking of reusing a single method.

I'm thinking of passing an extra parameter TypeInterface t and check type of this instance in the method and build objects of either A or B .

Most of the stuff in this method is common and hence i'm thinking of reusing a single method.

You will make the client API more verbose and complex by introducing an additional parameter that besides is a class.
As alternative you could declare two distinct public methods with a difference in their naming and in their implementation you could rely on a common private method for the common processings.

For example :

Suppose X the interface that A and B implement.

public X getA(String x, String y){
   X a = new A();
   // specificities for A ...
   ... 
   // common processing
   commonForGet(a);
   return a;
}

public X getB(String x, String y){
   X b = new B();
   // specificities for B ...
   ... 
   // common processing
   commonForGet(b);
   return b;
}

private void commonForGet(X x){
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM