views:

111

answers:

2

I am new to design patterns and I have a scenario here. I am not sure as how to implement the pattern.

  1. We have multiple vendors Philips, Onida, etc.
  2. Each vendor (philips, onida, etc) may have different types of product i.e. Plasma or Normal TV.

I want specific product of each vendor using Abstract Factory Pattern.

My implementation so far:

public enum TvType
{
    Samsung = 0, LG = 1, Philips = 2, Sony = 3
}

public enum Product
{
    Plasma = 0, NormalTV = 1
}

Concrete class of each vendor that returns each product and also the interface that contains ProductInfo i.e. if Vendor is that then it must have this product.

+1  A: 

In pseudocode it could be something like this:

interface TvFactory {
  NormalTelevision createNormalTv();
  PlasmaTelevision createPlasmaTv();
}

class PhilipsTvFactory implements TvFactory {
  public NormalTelevision createNormalTv() {
    return new PhilipsNormalTelevision();
  }
  public PlasmaTelevision createPlasmaTv() {
    return new PhilipsPlasmaTelevision();
  }
}

class OnidaTvFactory implements TvFactory {
  public NormalTelevision createNormalTv() {
    return new OnidaNormalTelevision();
  }
  public PlasmaTelevision createPlasmaTv() {
    return new OnidaPlasmaTelevision();
  }
}

// similarly for other vendors...

...
// decides - maybe based on config - which factory to use
TvFactory factory = loadTvFactory();
Television myTv = factory.createPlasmaTv();
Péter Török
In terms of deciding which factory to use, make the class that needs to use the factory abstract, and extending classes provide the factory that is then acquired by the base class by a call to its abstract getTvFactory method.
Finbarr
@Finbarr, that is one way to go, although I prefer a separate factory loader class. This makes the code reusable.
Péter Török
A: 

Enums are evil. Replace them with interfaces:

public interface IVendor { /*...*/ }

you can then provide concrete implementations of IVender for each of your vendors.

public class Samsung : IVendor { /*...*/ }

public class Philips : IVendor { /*...*/ }

public class Sony : IVendor { /*...*/ }

It's not clear to my why you are asking about Abstract Factory, or what it is you want to be able to do exactly...

Mark Seemann
Enums can implement interfaces :-)
Finbarr
@Finbarr, in some languages, yes. However, the language is not specified here. Judging from the code excerpt, it is not C++, neither Java - could it be C# ?
Péter Török
Yes... It is C#
Amit
Hey @Mark - As I mentioned earlier that I am new to pattern world... so just wanted to know how Abstract pattern can be implemented on such scenario.... nothing else... n e ways Thanks for u r comments.
Amit