How to apply Abstract Factory Pattern?
I am new to design patterns and I have a scenario here. I am not sure as how to implement the pattern.
- We have multiple vendors Philips, Onida, etc.
- 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:
pu开发者_StackOverflowblic 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.
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();
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...
精彩评论