Java Design Pattern: Abstract Factory

Abstract Factory pattern adds another layer of abstraction for Factory pattern. If we compare Abstract Factory with Factory, it is pretty obvious that a new layer of abstraction is added. Abstract Factory is a super-factory which creates other factories. We can call it "Factory of factories".

Abstract Factory class diagram

abstract-factory-design-pattern

Abstract Factory Java code

interface CPU {
    void process();
}
 
interface CPUFactory {
	CPU produceCPU();
}
 
class AMDFactory implements CPUFactory {
    public CPU produceCPU() {
        return new AMDCPU();
    }
}
 
class IntelFactory implements CPUFactory {
    public CPU produceCPU() {
        return new IntelCPU();
    }
}
 
class AMDCPU implements CPU {
    public void process() {
        System.out.println("AMD is processing...");
    }
}
 
class IntelCPU implements CPU {
    public void process() {
        System.out.println("Intel is processing...");
    }
}
 
class Computer {
	CPU cpu;
 
    public Computer(CPUFactory factory) {
    	cpu = factory.produceCPU();
        cpu.process();
    }
}
 
public class Client {
    public static void main(String[] args) {
        new Computer(createSpecificFactory());
    }
 
    public static CPUFactory createSpecificFactory() {
        int sys = 0; // based on specific requirement
        if (sys == 0) 
        	return new AMDFactory();
        else 
        	return new IntelFactory();
    }
}

Real use example

Actually, this is a very important concept of modern frameworks. Here is a question about this.

Category >> Design Patterns Stories  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. Davis Molinari on 2015-10-19

    I think Abstract Factory is a very powerful and flexible pattern that can be used in many cases to make a good design of the application domain. I also wrote the article “Design Patterns in real life: Abstract Factory” http://www.davismol.net/2015/03/18/design-patterns-in-real-life-abstract-factory/ where I described a real-case usage of it.

  2. Tomslayer on 2016-9-6

    This is a good real word example of factory pattern http://www.oracle.com/technetwork/java/dataaccessobject-138824.html

  3. Sicchi on 2017-1-12

    Java is an excellent programming language but if u want looking for something better u can search here UG Library

Leave a comment

*