Created
February 14, 2013 03:18
-
-
Save JoshCheek/4950348 to your computer and use it in GitHub Desktop.
Java Factory example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class A { | |
public static void main(String[] Args) { | |
A a = new A(new B1Factory()); | |
System.out.println(a); | |
a = new A(new B2Factory()); | |
System.out.println(a); | |
} | |
private BFactory factory; | |
public A(BFactory factory) { this.factory = factory; } | |
public String toString() { | |
return "<A containing the b: " + factory.b() + ">"; | |
} | |
static interface BFactory { | |
public B b(); | |
} | |
static interface B { | |
public String toString(); | |
} | |
static class B1Factory implements BFactory { | |
public B b() { return new B1(); } | |
} | |
static class B1 implements B { | |
public String toString() { return "b1"; } | |
} | |
static class B2Factory implements BFactory { | |
public B b() { return new B2(); } | |
} | |
static class B2 implements B { | |
public String toString() { return "b2"; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment