Instantly share code, notes, and snippets.

Embed
What would you like to do?
FactoryMethod Pattern
// http://ja.wikipedia.org/wiki/Factory_Method_%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3
public class FactoryMethodSample {
public static void main(String[] args) {
Creator creator;
Product product;
creator = new CreatorA();
product = creator.factoryMethod();
product.whoAreYou();
creator = new CreatorB();
product = creator.factoryMethod();
product.whoAreYou();
}
}
abstract class Creator {
abstract Product factoryMethod();
}
class CreatorA extends Creator {
Product factoryMethod() {
return new ProductA();
}
}
class CreatorB extends Creator {
Product factoryMethod() {
return new ProductB();
}
}
abstract class Product {
abstract void whoAreYou();
}
class ProductA extends Product {
void whoAreYou() { System.out.println("I'm A");}
}
class ProductB extends Product {
void whoAreYou() { System.out.println("I'm B");}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment