Abstract Factory Design Pattern

Could someone please explain the abstract factory design pattern in simple english. As far as I understand it is used to create a bunch of related objects based on parameter/s provided at runtime.
However, why would one use this compared to an Interface.
I actually am reading a great book on design patterns (Design Pattern by James Cooper) but having a bit of problem really understanding this one.
Cheers

As far as I
understand it is used to create a bunch of related
objects based on parameter/s provided at runtime. There may be variations but as I understand it basically an Abstract Factory defines two interfaces, one is the factory and one is the product. A good example is iterators in Java. The iterator factory is the Iterable interface and the iterator product is the Iterator interface.
ArrayList implements Iterable so it's an iterator factory. If you call the iterator() method of an ArrayList object you'll get an Iterator object. The same applies to TreeSet and many other classes.
The Iterator objects sport the same Interface but they're quite different internally of course (Iterating an array is not the same as iterating a tree) so they're a "family of related products".

Similar Messages

  • Examples of the Abstract Factory Design Pattern

    Could someone please give an example about situations in which you would definitly use the Abstract Factory Design Pattern?

    Ok, but they are coupled because Abstract Factory uses Factory methods. Without getting too detailed here, Abstract Factory is useful when you want to swap out entire sets of things (ie. pluggable look and feels). So one subclass of AbstractGUIFactory is MotifGUIFactory while another is WindowsGUIFactory. Your application can gets a specific factory but puts it in an AbstractFUIFactory variable.
    AbstractGUIFactory factory = new WindowsGUIFactory();
    AbstractButton = factory.makeButton();So you can program generically and swap out entire sets of widgets by changing one line of code.
    You should really read Design Patterns by Gamma et al. because it is the definitive book on this topic.

  • Factory design pattern use

    Hi people, I have a question about a design I'm using.
    Lets say I have an object that can be a number between 1 and 100, or another couple of values such as not defined or implicit.
    I had a basic design that looked like this:
    public final class ObjectExample
        public static final ObjectExample NOT_DEFINED = new ObjectExample(-1);
        public static final ObjectExample IMPLICIT = new ObjectExample(-1);
        public static final ObjectExample createObjectExample(int value)
            if ((value < 1) || (value > 100))
                throw new IllegalArgumentException("Value is not valid");
            return new ObjectExample(value);
        private final int value;
        private ObjectExample(int value)
            this.value = value;
        public int getValue()
            return value;
    }Now this code does what I need, I was just wondering about the merits of using a factory method to create the objects. Why shouldn't I just move the logic of checking the value of the supplied value to the constructor and make that public?
    Basically, what I suppose I'm asking is, in this particular example, is there any need to use a "factory" method to create objects?
    Cheers, Boomah :o)

    In this particular case you could certainly put that logic in a constructor. However if you decided you wanted to use a Flyweight pattern and only have one instance of ObjectExample(1) instead of many, then you would need a factory method that created that one instance and always returned it when called with 1 as its parameter. You couldn't do that with a constructor.

  • Factory Design Pattern with Java generics

    I was wondering if it was possible to implement the factory pattern using a generic like sintax with java5. Something like:
    IFactory factory = new ConcreteFactory();
    Car c=factory.CreateObject<Car>();
    I saw this article the other day http://weblogs.asp.net/pgielens/archive/2004/07/01/171183.aspx
    done in C# for the framework 2.0 and tryed to re-implement it with java5 however I was less then fortunate, can someone do a functional conversion?

    I had to change the signature a bit but this is the best I came with:
    (I don't like I have to write Type.class but if someone has a better idea please share, I deliberatly used classes are return types but you can easily program to the interfaces as well)
    use:
    ConcreteFactory cf=new ConcreteFactory();
    Car c=cf.Create(Car.class);
    public interface Vehicle {
    String getName();
    public class Plane implements Vehicle {
    String name="Mig 29";
    public String getName() {
    return name;
    public class Car implements Vehicle {
    String name="Volvo";
    public String getName() {
    return name;
    public interface IFactory{
    <T> T Create(Class<T> type);
    public class ConcreteFactory implements IFactory {
    public <T extends Vehicle> T Create(Class<T> type) {
    try {
    return type.newInstance();
    } catch (InstantiationException e) {
    return null;
    } catch (IllegalAccessException e) {
    return null;
    }

  • Using IOC with Factory Design pattern

    Say I have two different data sources, one XML and another Database.I have 2 DAO's corresponding to the 2 data source and a DAOFactory to get the DAO.
    Now, I want to use IOC from the service layer to get appropriate DAO. Using DAOFactory will break IOC.
    Will it be a good idea to inject DAOFactory into the service layer?
    I somehow don't feel comfortable in doing so, Factories seem to be more or less like utility and injecting utility into the service does not seem a good idea to me.
    Please let me know how to get around this situation.
    Regards,
    Joshua

    JoshuaAntony wrote:
    Say I have two different data sources, one XML and another Database.I have 2 DAO's corresponding to the 2 data source and a DAOFactory to get the DAO.
    Now, I want to use IOC from the service layer to get appropriate DAO. Using DAOFactory will break IOC.
    Will it be a good idea to inject DAOFactory into the service layer?
    I somehow don't feel comfortable in doing so, Factories seem to be more or less like utility and injecting utility into the service does not seem a good idea to me.To me, this sounds like you're getting bogged down in abstract terminology and worrying about vague "rules" rather than considering the problem. Do you even need a DAOFactory? As the other guy said, a DAO interface, implemented however you like, injected where it's needed, is nice and simple, and avoids all those bothersome factories you probably don't need

  • Builder Design Pattern

    Hi,
    I'm trying to implement the Abstract Builder design pattern for a fairly complex object. If I understand correctly, the builder creates the whole object in one shot; as in, the pieces are hidden from the client while the object is being built. So suppose the object that I need to include as an "ingredient" is more complex. I have a class called Route (with different types that extend it) that requires a list of segments and an origin and destination. The part I'm confused on is how to build a route if I can't provide parameters for it. All the examples I've found so far have had simple objects for the ingredients that didn't require any personalization. Sorry if I'm being unclear. Ask if you need clarification.

    Could be. I'm far from a pattern guru. The key here is to find an approach that works. If perusing a catalog of patterns give you and idea of how to solve your problem, great, use it. On the other hand, if you already have a solution, and it happens to fit a pattern, then cool, now you have a name for what you did. The wrong thing to do would be to try to force it into a particular pattern that doesn't fit.
    The value in patterns is twofold: 1) as a means of communication of some fairly complex, commonly used, abstract concepts, as in, "I suggest a Builder Pattern for this," and the other guy knows exactly what you're talking about, or at least has a general idea and knows where to go for details, and 2) as a catalog of common solutions to existing problems, as in, "Dang it, I have this problem with such-and-such interactions among the pieces, I'm not sure how to structure a solution, but I bet somebody else has done it before... Oh, yeah! Builder Pattern! That'll work!"

  • Factory v/s Facade Design Pattern.

    Folks,
    I was just going thru the Design Patterns (Factory Pattern and the
    Facade Pattern)
    The Factory Pattern :
    The factory completely abstracts the creation and initialization of the product from the client
    This indirection enables the client to focus on its discrete role in the application without concerning itself with the details of how the product is created. Thus, as the product implementation changes over time, the client remains unchanged.
    Client--------------------->Factory----------------->Product
    The Facade Pattern
    Encapsulate the subsystem using a High-Level Interface/provides a
    simplified and uniform interface to a large subsytem of classes.
    The Client communicates with the 'Facade' which has methods to interact
    with subsystems.The Client very rarely accesses objects in the subsystems.
    Subsystems objects usually retain no knowledge of the client.
    Subsystem objects do not normally maintain any reference to Fa�ade.
    Client------------------->Facade------->Subsystems
    My Question is this:
    Arent both these pattern quite similar becos both designs access an Interface
    which inturn invokes the required object of the subsystems?
    Can anyone explain the major difference?

    Perhaps these definitions will clarify things a little for ya...
    Fa�ade
    The Fa�ade pattern simplifies access to a related set of objects by providing one object that all objects outside the set use to communicate
    with the set. This also promotes a weak coupling between the subsystem and its clients. This weak coupling allows you to vary the
    components of the subsystem without affecting the clients.
    Factory
    Centralize the assembly of resources necessary to create an object. This prevents the need to change all classes from changing when a
    Product changes and makes any change needed occur only in the Factory.

  • Design Patterns: 'Program to an interface, not an impl.' and Factory Method

    Design Patterns: 'Program to an interface, not an implementation' and Factory Method.
    Hi All,
    I've 4 questions. And 1M thanks for your precious input.
    1. OOAD steps:
    Requirement-->Use Cases-->Analysis Classes-->Sequence Diagrams-->CRC-->other UML diagrams if needed--> Domain/Business Classes.
    If we follow the rule 'Program to an interface, not an implementation',
    would that imply NECESSARILY we should have another set of Interface Classes for our Domain Classes? i.e Interface_ClassX for ClassX_Impl.
    2. If the point 1 is a MUST because of the rule 'Program to an interface, not an implementation',
    ie we should have an Interface classe for every one Domain classe,
    would that NECESSARILY imply we should have as many Factory Methods as they are Domain Classes to abstract the creation process?
    Interface_ClassX X= Factory.GetClassX() ( return new ClassX_Impl)
    Interface_ClassY Y= Factory.GetClassY() ( return new ClassY_Impl)
    Interface_ClassZ Z= Factory.GetClassZ() ( return new ClassZ_Impl)
    3. On the point 2, the underlying principle used is Factory Methods.
    Now on the surface, what are other possible business and/or technical naming for such Factory Methods? I mean should we call it a kind of Business Facade?
    4. Is the point 1 and point 2 considered to be the best practices?

    So the question here is whether we can predict having
    more than one possible implementations which required
    option c. Is this a dilema? I guess it's hard to
    predict the future.Right. Hopefully it's fairly obvious while designing things and
    deciding what objects are needed.
    Now, if the Presentation Tier, says JSP, needs that
    ClassNormal object. Would we still keep that line of
    code a.
    OR would we introduce an intermediate object to free
    JSP from the direct creational aspect using new
    keyword like the choice b. that you reject.
    The point here is to reduce the direct coupling aspect
    between the Presentation Tier and Business Tier. So
    what would that intermediate object be?In that case, you have to ask yourself if there is a valid
    need for reducing the coupling. If you simply make an intermediate
    object, what keeps you from making an intermediate object to your
    new intermediate object, ad infinitum.
    That intermediate object could be a Facade pattern, or simply
    an abstraction. We actually did that here, we began a massive
    java project, and we abstracted away from Swing J-classes and created
    our own "wrappers" that simply extended all the J-classes and we had
    all our programmers develop using our wrappers instead of the Swing
    classes. That allowed us to add some custom code, some temporary bug fixes, etc. Some of our classes were nothing more than "EPPasswordField extends JPasswordField" with nothing overridden. It does allow us a place to hook in and adjust or fix things if needed though.

  • BlazeDS and Abstract Factory Pattern

    Hi All,
    I was trying to extend my application using the Factory Method. But, I identified that I need to use an abstract Factory pattern to meet my design requirements. In other words I need to create a FactoryInstance based on a input. Will that be possible.
    Any help?????
    -Ram V

    The Factory pattern is meant to give you the ability to generically construct objects (rather than explicitly declare what you want to create via the "new" keyword you defer to a factory and take what it gives you) The Abstract Factory pattern is meant to give you the ability to generically construct Factories. So, for instance, say you want to create widgets with a certain look and feel. You could use the Factory pattern and ask a ButtonFactory to make buttons and a TextArea factory to make TextAreas, but since you want the same look and feel for all widgets you could just ask the WidgetFactory to give you a WidgetFactory for a given Look and Feel and then ask it to make Buttons and TextAreas and whatever else, knowing that it has handled which kind of button and whatever else you need.
    Hope that made sense, good luck
    Lee

  • [DESIGN PATTERN] Factory: Define Method Area

    Hi Guys,
    I have a question regarding the Design Pattern:Factory. According my need the question is below as:
    I have the Abstract Class AAA with it own Abstract method that create objects (only one method).
    I have a Final Sub-Class  BBB with 20 instantiate methods + the inherited method from Class AAA.
    BBB->method_bbb1().
    BBB->method_bbb2().
    BBB->method_bbb3().
    I have a Final Sub-Class  CCC with 10 instantiate methods + the inherited method from Class AAA.
    CCC->method_ccc1().
    CCC->method_ccc2().
    CCC->method_ccc3().
    Afterwards:
    Class BBB is instantiated through the Factory. The TYPE of BBB is AAA.
    Class CCC is instantiated through the Factory. The TYPE of CCC is AAA.
    My question is:
    How could I use the 20 methods of BBB without to declare them in AAA (without inheritance). Because, if I declare them in AAA, consequently they will be visible in CCC. And I don't want to ...
    DATA BBB TYPE REF TO AAA. "Var Object BBB is type of Class AAA
    DATA CCC TYPE REF TO AAA. "Var Object CCC is type of Class AAA
    BBB = AAA=>Factory( 'BBB' ).
    CCC = AAA=>Factory( 'CCC' ).
    " I want to call, in that way:
    BBB->method_bbb1().
    CCC->method_ccc1().
    CCC->method_bbb1(). " RAISE ERROR
    I have found a way but I don't know if it's breaking the rules of the Factory Concept.
    Have you got any idea?
    Thank you in advance.
    Rachid.

    Hi,
    If you have declared the methods in abstract class as protected or public and if you are inheriting it to the sub classes, then the methods will be available in the subclasses. There is no way to restrict like few abstract methods needs to be inherited and others need not be inherited. The inherited classes are forced to implement the abstract methods.
    In your scenario, i do not think there is a need of abstract class, as I assume that both of your classes does some stand alone logic( as per your question ) compared to the other and doesn't have any common operations. Could you please let us know about this in detail ?? What about INTERFACES ?, Please have a look into it.
    Kesav

  • Design-pattern(Factory)

    can any body tell me under which sceniro it would be beneficial to use factory and abstract factory pattern
    thanks in advance

    We will need to use a factory pattern when we want to delegate the logic of creation of classes to a different class. This class holds the responsibilty of handling the creation of the the range of realated Objects of the same type.
    Ex: In an ice cream parlour the cones are the same and the method of filling in the cones is also the same, only thing that differs is the cream that needs to be filled. Delegate this responsibility to a factory method.
    You will go for an abstract factory pattern if you have the a class which itself has several varieties and even the compose classes within this class has several varieties.
    Ex: Extending the above example if there are range of cones available to choose from and a range of cream to choose from we will go for an abstract factory.

  • Could someone explain the Factory Method Design Pattern

    Hi Experts.
    Could someone please explain for me the Factory Method Design Pattern. I read it a little and I understand that it is used in JDBC drivers but i'm not clear on it.
    Could someone explain.
    Thanks in advance
    stephen

    Basically, you have one class that's sole purpose is to create instances of a set of other classes.
    What will usually happen is you have a set of related classes that inherit from some base class. We'll say for example that you have a base class CAR and it has sub-classes FORD, GM, HONDA (sorry Crylser). Instead of having the user call the constructors for FORD, GM, and HONDA, you can give the user a Factory Class that will give him a copy. We'll call our factory class Dealership. Inside dealership, you can have a static function :
    public static Car makeCar(String type)
    if(type.equals("FORD")
    return new FORD();
    else if(type.equals("GM")
    return new GM();
    else if(type.equals("HONDA")
    return new HONDA();
    So when the user needs a car, they will just call
    Dealership.makeCar("FORD").
    This is a good way to hide the implementation of your classes from the user, or if you require complex initialization of your objects.
    Another good example of this is in the Swing library. To get a border around a component, you call static methods on BorderFactory.
    Hope this helped.
    Ed

  • Abstract Factory Pattern

    Hi All
    I have created the abstract class as shown below and I've got a number of concrete classes which implements it. When getFactory(String name) is called it addes an instance of a concrete class to the hashtable in the abstract class.
    My issue is that I would like all the concrete class to be added automatically (somehow) to the hashtable or have a method that gives my an overview of the available concrete classes so that a client can ask for them and then choose which one to pick. Is there a way to achieve this
    (PS: the KPI interface which is implemented only holds some public static fields)
    Thanks in advance
    Thomas
    import java.util.Collection;
    import java.util.Hashtable;
    * KPIFactory is declared abstract and requires implementation of the business methods
    * for each KPI.
    public abstract class KPIFactory implements KPI {
         * public static Hashtable which containes all the added KPIFactories
         * instances
        private static Hashtable KPI_FACTORIES = new Hashtable();
         * addFactory returns a KPIFactory from the given name.
         * <p/>
         * If the KPIFactory isn't already in the static Hashtable it will be
         * added if it can be found. All the Factories extending this class
         * will have a static body which adds it when class.forname is called.
         * If it cannot be found a KPINotFoundexcpetion is thrown
         * @param name of the class which implementes the KPIFactory
         * @return returns a KPIFactory if the
        public static KPIFactory getFactory(String name)
                throws KPINotFoundException {
            KPIFactory s = (KPIFactory) KPI_FACTORIES.get(name);
            if (s == null) // KPI not found
                try {
                    Class.forName(name);
                    // By now the static block in the KPI implemenation
                    // would have been executed, which addes a new instance
                    // to the static hashtable.
                    s = (KPIFactory) KPI_FACTORIES.get(name);
                    if (s == null) // Error is KPI isn't found now
                        throw (new KPINotFoundException());
                } catch (ClassNotFoundException e) {
                    // throws an exception to indicate that
                    // the KPIFactory could not be created
                    throw(new KPINotFoundException());
            return (s.create());   // Returns an instance of the KPIFactory
         * addFactory takes the manufactored object kpi and
         * puts it into the hashtable with the name as the key
         * <p/>
         * The method is syncronized in order to avoid problems with mutliple
         * factories writting to the hashtable at the same time
        public static synchronized void addFactory(String name, KPIFactory kpi) {
            KPI_FACTORIES.put(name, kpi);
         * create is abstract and returns a KPIFactory.
         * <p/>
         * create is implemented in every concrete class which
         * extends the KPIFactory and it returns an instance of
         * the concrete class (and therefore KPIFactory as the
         * super class)
         * @return returns a KPIFactory
        public abstract KPIFactory create();
        public abstract void calculate(KPIDataset dataset);
    }

    Hi,
    One "elegant" solution that comes to mind is to use AspectJ, for which you'd define as Aspect something like this:
    public aspect FactoryRegistrationAspect {
    /* A pointcut for calls to all implementing classes of KPIFactory */
    pointcut registerFactory (KPIFactory kpif, String name) :
    call (* * KPIFactory.getFactory(String)
    && within(KPIFactory+)
    && target(kpif)
    && args(name);
    /* When the above pointcut occurs, execute the following advice and invoke the registerIfNecessary
    method in your Abstract Factory clalss */
    before(KPIFactory kpif, String name) : registerFactory(kpif, name) {
    kpif.registerIfNecessary(name);
    In your abstact factory class, you'd then have the registerIfNecessary(String name) method. Which would look something like this:
    public boolean registerIfNecessary(String name) {
    if (!KPI_FACTORIES,containsKey(name)) {
    try {
    Class clazz = Class.forName(name);
    KPI_FACTORIES.add(name, (KPIFactory)clazz.newInstance());
    return true;
    catch (Exception e) { return false}
    The "magic" behind aspectJ is that it weaves the addition from the aspect into your implementing classes during compile time such that you don't need any property files etc to define your implementing classes, its all done by the aspecJ compiler during compile time.
    If the above is unlike what you've seen, check out the magic at eclipse.org/aspecj and get in on the greatest thing ever devised since OOP.
    Cheers
    Bones

  • Factory design question

    Is it gospel that a Factory be static? For instance, I'd like to have a Factory class that I maintain a reference to and returns me the correct instance of an object, which I invoke methods on. However, I want the Factory class to hold onto all the references while I have another object which maintains the reference to the Factory. I know this is possible, but I don't know if I'm violating a best practice here. Every time I read about an Abstract Factory, it is used with a static reference. Or is this a completely different kind of design pattern?

    No, for instance, I'd like it to be this way. Assume Dog and Cat inherit Animal and have all the required methods.
    MyObject will maintain a reference to the Factory, which will in turn maintain all my necessary references. The client code will only call feedAnimal or walkAnimal on MyObject. My question is, is this poor design or violating any best practices?
    public class MyObject {
       AnimalFactory af;
       public MyObject() {
           af = new AnimalFactory();
       private Animal getAnimal(String name) {
            Animal al = af.getInstance(name);
            return al;
       public void feedAnimal(String name) {
            getAnimal(name).feed();
       public void walkAnimal(String name) {
            getAnimal(name).walk();
    public class AnimalFactory {
       public AnimalFactory() {
       public Animal getInstance(String s) {
             Animal al;
             if (s.equals(ROVER)) {
                  al = new Dog();
             } else if (s.equals(WHISKERS)) {
                  al = new Cat();
             return al;
    }

  • Design patterns for Dynamic Class Loading

    Hi,
    I have to develop a program for uni that dynamically loads classes based on names in a text file. All the classes subclass an abstract class with a constructor that takes one argument. This means I can't use the Class.forName(className).newInstance() method of class loading. I have researched some design patterns I could use and have come up with the following 3:
    Factory pattern; "Robocode" pattern (not it's real name, but Robocode uses it); and, the "one I made up myself" pattern.
    The robocode pattern instantiates a class using the default no-argument constructor then immediately sets all properties that shoud have been provided in the constructor:
    Object o = Class.forName(myClass).newInstance();
    o.setProperty(property);Personally I think this is ugly and a cheap fix instead of doing it properly.
    My own pattern finds the constructor that takes the arguments I need then calls it to create the object:
    Class c = Class.forName(myClass);
    Constructor cons = c.getConstructor(new Class[]{Class.forName("java.lang.String")});
    Object o = cons.newInstance(new Object[]{"hello"});What's the best to use? Are there any other patterns I should consider?

    My own pattern finds the constructor that takes the
    arguments I need then calls it to create the object:
    Class c = Class.forName(myClass);
    Constructor cons = c.getConstructor(new
    Class[]{Class.forName("java.lang.String")});
    Object o = cons.newInstance(new Object[]{"hello"});
    I have followed this basic 'pattern' several times though I would use
    Constructor cons = c.getConstructor(new Class[]{String.class});
    It works great.

Maybe you are looking for

  • How do I set up two iPods (nano and touch) on the same computer?

    I have to configure two Ipod (touch and nano) on the same computer but with two different music libraries. It can be done?How? Thank

  • How do u delete the history for search page on search iPhone?

    When you slide all the way to the left on your iPhone, search iPhone window is there. On this page, there's a search bar and you type in whatever you need to search and hit search web or search Wikipedia but also below that is options for if what you

  • Programmatically making the ADF page dirty

    In ADF page, I have a form to add one record. When I add one record, it adds record to temporary list to a bean which is in viewscope. The temporary records list will be displayed below the form as a table data. There is button for final commit once

  • NWDS imports wrong DC Version

    Hello, for this problem i have altready an OSS message open, but maybe someone has a solution for this problem, because we are a bit in hurry. My whole JDI and NWDS is SPS14. I created External Library DC`s (EXTLIBS) and connected this track to anoth

  • Have faces on iPhone photos when none are checked to appear

    Why do all faces in iPhoto appear on the iPhone? In iTunes, the sync section of photos has selected albums, Events, etc checked with  No Events chosen. None of the face entries in the section below of iTunes are checked. I would assume faces wouldn't