-1

I have a use-case like this:

Based on the parameter passed - I have to create an object corresponding to it but the underlying functionality remains same.

public void selectType ()
{
  String type = "ABC";
  publishType(type);
}

public void publishType(String type)
{
if (type.equals("ABC"))
ABCtype publishObject = new ABCtype();

if (type.equals("XYZ"))
XYZtype publishObject = new XYZtype();

publishObject.setfunctionality();
}

What is a better way to approach this? Which design pattern does it fall in?

Another doubt I have is - how to initialize publishObject? It gives an error like this.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
R11G
  • 1,941
  • 8
  • 26
  • 37

1 Answers1

1

but the underlying functionality remains same

you maybe consider design suing interfaces..

Do some nice Archi- Design like:

define an interface, and 2 classes that implement the interface, then declare an object foo and initialize it according to the parameter..

Example:

interface IObject{
    //methods here
}
class A implements IObject{}
class B implements IObject{}

public void selectType ()
{
    IObject foo = getObject(1);
}

public IObject getObject(int type){
    if (type ==1){
        return new A();
    }else{
        return new B();
    }
}
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97