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;
}

Similar Messages

  • 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".

  • 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.

  • Producer/Consumer Design Pattern with Classes

    I'm starting a new project which involves acquiring data from various pieces of equipment using a GPIB port.  I thought this would be a good time to start using Classes.  I created a GPIB class which contains member data of:  Address, Open State, Error; with member vis such as Set Address, Get Address, Open, Close...general actions that all GPIB devices need to do.  I then created a child class for a specific instrument (Agilent N1912 Power Meter for this example) which inherits from the GPIB class but also adds member data such as Channel A power and Channel B power and the associated Member Functions to obtain the data from the hardware.  This went fine and I created a Test vi for verfication utilizing a typical Event Structure architecture. 
    However, in other applications (without classes) I  typically use the Producer/Consumer Design Pattern with Event Structure so that the main loop is not delayed by any hardware interaction.  My queue data is a cluster of an "action" enum and a variant to pass data.  Is it OK to use this pattern with classes?  I created a vi and it works fine and attached is a png (of 1 case) of it.
    Are there any problems doing it this way?
    Jason

    JTerosky wrote:
    I'm starting a new project which involves acquiring data from various pieces of equipment using a GPIB port.  I thought this would be a good time to start using Classes.  I created a GPIB class which contains member data of:  Address, Open State, Error; with member vis such as Set Address, Get Address, Open, Close...general actions that all GPIB devices need to do.  I then created a child class for a specific instrument (Agilent N1912 Power Meter for this example) which inherits from the GPIB class but also adds member data such as Channel A power and Channel B power and the associated Member Functions to obtain the data from the hardware.  This went fine and I created a Test vi for verfication utilizing a typical Event Structure architecture. 
    However, in other applications (without classes) I  typically use the Producer/Consumer Design Pattern with Event Structure so that the main loop is not delayed by any hardware interaction.  My queue data is a cluster of an "action" enum and a variant to pass data.  Is it OK to use this pattern with classes?  I created a vi and it works fine and attached is a png (of 1 case) of it.
    Are there any problems doing it this way?
    Including the error cluster as part of the  private data is something I have never seen done and ... well I'll have to think about that one.
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Design metasearch with java

    hi,
    i'm student in computer science and engineering at faculty of electronic engineering
    and i want to design metasearch with java
    can you provide me with some resources about this topic

    please i don't understand
    can you explain more?If you are designing a metasearch with java
    and your first question is: "can you provide me with some resources about this topic?"
    Then it looks like you have tough road ahead of you.
    One thing that will be very helpful:
    www.google.com

  • Desperately trying to find patterns with Java code samples

    Greetings. Is there anyone who knows where I can find Java patterns, I am particularly looking for template, literator, composite, observer and decorator. I have gone to Hillside and Portland Repository sites, but did not find pattern sample code.
    I bought the head first Java book which I love, but I would like to see more sample code. They mention pattern catalogues, and besides the Gof I cannot find any. I really want to look at loads of actual samples to get a real feel how these patterns can be applied. Where can I go please?
    Thank you for any and all help.
    Peace,

    You're most welcome - you might check out the Head
    First Design Patterns book as well.Yes, that was fun to read!

  • ETL design pattern with Data Integrator

    Hi all
    I have searched a lot on the SAP website and also on the Google to find a reliable document about ETL design pattern which applies to BO Data Integrator, but it was not successful. Most of the links I found was for  SSIS and Informatica,....
    I would be grateful if you could guide me to a good link about ETL design pattern.
    Thanks.

    I would start with these two:
    https://wiki.sdn.sap.com:443/wiki/display/BOBJ/ETLProjectGuidelines
    https://wiki.sdn.sap.com:443/wiki/pages/viewpage.action?pageId=49414406

  • 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

  • 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.

  • Design Patterns for java swing application front a J2EE server

    Hi,
    i dont nkow that i stay in the correct forum. I am development a java swing client application, no web, and i dont know that if there are any patterns for a client of this type.
    I have readed http://java.sun.com/blueprints/corej2eepatterns/Patterns/index.html
    but after of Buissnes Delegate pattern, the others one, over ejb tier, are applicated only for web clients, using servlets and jsp pages.
    If i have a swing client application, what patterns i must folow for implement the client logic of my swing application??
    thanks

    MVC pattern is one of the most used
    http://en.wikipedia.org/wiki/MVC
    http://csis.pace.edu/~bergin/mvc/mvcgui.html
    ...

  • Localization design patterns with TopLink

    Hello,
    We are creating web app with JSF and TopLink.
    Each table in database may have several fields that can be localized.
    All localization resources are stored in a table that has such columns: table_name, column_name, language, localized_text.
    How would you suggesting implement localization using TopLink?

    Sorry, I missed one column.
    Columns in localization table: table_name, column_name, row_id, language, localized_text.

  • How i can start working with Java?

    Right now i am having only 8 months of exp in ABAP. can any one help me out to start working with Java specially for Netweaver Purpose

    It is great if you can get yourself familiar with java syntax, as is the case with any new langauage. However, the worst thing you can do is just code java in a top down approach. If you are not familiarizing yourself with OO concepts and best practices, then you are going to miss two important benefits that you will get from using OO programming - Reusability and flexibility in the frameworks that you develop (leveraging design patterns).
    These benefits will also be directly obtainable when you use ABAP objects.
    I am working in the opposite direction at the moment. I have some java experience, and I am starting to learn ABAP. I have used ABAP objects in my first project, and it was actually much better than I thought it would to be.
    Java and OO programming will be an ongoing learning experience. You will not be an expert for quite some time. I do not consider myself to be an expert by any means, and I've be studying OO and java for a few years.
    There is a fantastic book that explains OO concepts clearly, in much easier terms than the Gof "Design Patterns" book:
    Java Design: Objects, UML, and Process by Kirk Knoernschild
    You can read a few chapters at www.kirkk.com. (Use the JOUP link).
    Hope this helps you.
    - Brendan

  • Design Patterns Web Site

    Hi,
    I was curious what everyone's opinion (or at least those who frequent this forum) was about a website explaining Design Patterns using Java.
    I was thinking about making a site which discusses various design patterns, including real-world analogies (to try and make things simple and clear), and sample code.
    i thought it might be a good idea, b/c I myself am trying to learn about design patterns (including when to use them and when not to use them)....and there is a lot of info on the web, but I learn best by example....so thats wherei got the idea for a straight forward site.
    what are your thoughts? I kind of like the style of O'Reilly's "Head First Design Patterns" as an approach. Let me know what u think..
    peace.
    craig

    wow, thats what i had in mind...and since a lot of the samples are C#...its easy to relate to java.
    thanks

  • Factory Patterns with Generics

    I am trying to combine the good old factory pattern with generics and could use some advice.
    I have the following
    //Base class from which all my things extend
    public abstract class Thing {
    //one kind of thing
    public class ThingOne extends Thing {
    //another kind of thing
    public class ThingTwo extends Thing {
    //interface for my factory
    public interface ThingFactory<T> {
    public T create(long id);
    //a factory for thingones
    public class ThingOneFactory<T> implements ThingFactory<T> {
    public T create(long id) {
    return (T) new ThingOne();
    public class TestClass{
    public <T extends Thing> T getThing(ThingFactory<T> tf){
    //do a bunch of generic stuff to figure out id to call create
    ThingFactory<T> instance = tf;
    return (T) instance.create(Long id);
    }My calling code would know what kind of thing it needs but necessarily the things id. Which can be computed in a generic way.
    TestClass gt = new TestClass();
    gt.getThing(new ThingOneFactory<ThingOne>());This all seems to work properly but I am getting "Type safety: Unchecked cast from ThingOne to T" in my ThingOneFactory
    My T's will always extend Thing, what am I missing? Is there a better way to do this?
    Edited by: nedry on Dec 29, 2009 5:39 PM

    I thought of that after I posted. But that just moves my unsafe cast warning into TestClass.Why?
    return (T) instance.create(Long id);That can't have ever compiled. What is the exact code? And why did you have to cast (what was the warning/error)?

  • Software reuse with Java design patterns

    Anyone have any suggestions on how software can be reused with Java design patterns? Any concrete examples?

    Buy the GoF book. Lot's of examples there.

Maybe you are looking for

  • Find Window disappearing off top of screen

    A colleague's find window is 'stuck' off the top of the screen! The lower part is visible. Reset/change workspace doesn't help. We've also tried System Prefs - Display - Gather Windows but that didn't work either. Googling suggests it's  not a common

  • Hi i want to how to use DTO in struts frame work.

    hi all, i want to display content on jsp pages using DTO object. in my application one jsp page for user input. foruser input i am creating one action form for this. and also one DTO class for handing action form . my main aim is elimunate the action

  • HELP.... My website disapeared from iweb!!!

    I'm panic struck... I opened iweb and my website simply was not there! Even though I saved always and repeatedly. I've been building my personal website and just finished a particularly dificult page, with a ton of videos and stuff. I saved and quit,

  • [new x11/window manager] WindowMaker 0.92 PKGBUILD

    Here is the PKGBUILD for WindowMaker 0.92: pkgname=windowmaker pkgver=0.92.0 pkgrel=1 pkgdesc="An X11 window manager with a NEXTSTEP look and feel" depends=('x-server' 'libtiff' 'libungif' 'libpng' 'libjpeg') source=(ftp://ftp.windowmaker.org/pub/sou

  • Shared Session

    Hello we need a session-store (maintaining state) which is shared between several WebDynpros. The WebDynpros are embedded into the Portal as iViews, any hint how to get such a shared session-store? Thanks! Kai