Skip to content

Instantly share code, notes, and snippets.

@shoheiyokoyama
Last active August 4, 2017 00:08
Show Gist options
  • Save shoheiyokoyama/9560aef57d71cbfec22b to your computer and use it in GitHub Desktop.
Save shoheiyokoyama/9560aef57d71cbfec22b to your computer and use it in GitHub Desktop.
デザインパターン「Factory Method」 ref: http://qiita.com/shoheiyokoyama/items/d752834a6a2e208b90ca
public class Account extends Product {
private String owner;
Account(String owner) {
System.out.println("Create account: " + owner);
this.owner = owner;
}
public void use() {
System.out.println("Use account: " + owner);
}
public String getOwner() {
return owner;
}
}
public class AccountFactory extends Factory {
private List owners = new ArrayList();
protected Product createProduct(String owner) {
return new Account(owner);
}
protected void registerProduct(Product product) {
owners.add( ((Account)product).getOwner() );
}
public List getOwners() {
return owners;
}
}
class Factory {
AbstractDataReader create(int formatId) {
AbstractDataReader reader = null;
if (CSV == formatId) {
reader = new CSVDataReaderd();
} elseif (XML == formatId) {
reader = new XMLDataReaderd();
}
return reader;
}
}
Create account: Ralph Johnson
Create account: Richard Helm
Create account: John Vlissides
Create account: Erich Gamma
Use account: Ralph Johnson
Use account: Richard Helm
Use account: John Vlissides
Use account: Erich Gamma
AbstractDataReader reader = null;
if (CSV == formatId) {
reader = new CSVDataReaderd();
} elseif (XML == formatId) {
reader = new XMLDataReaderd();
}
data = reader.read();
AbstractDataReader reader = null;
Factory factory = new Factory;
reader = factory(formatId);
data = reader.read();
public static void main(String[] args) {
Factory factory = new AccountFactory();
Product account1 = factory.create("Ralph Johnson");
Product account2 = factory.create("Richard Helm");
Product account3 = factory.create("John Vlissides");
Product account4 = factory.create("Erich Gamma");
account1.use();
account2.use();
account3.use();
account4.use();
}
public abstract class Product {
public abstract void use();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment