类图:
实现:
Product.java:
package com.factory.simple;
public interface Product {
public void printName();
}
ProductA.java
package com.factory.simple;
public class ProductA implements Product{
@Override
public void printName() {
System.out.println("product A");
}
}
ProductB.java
package com.factory.simple;
public class ProductB implements Product{
@Override
public void printName() {
System.out.println("product B");
}
}
Factory.java
package com.factory.simple;
public class Factory {
public static Product create(String name) {
if ("A".equals(name)) {
return new ProductA();
} else if ("B".equals(name)) {
return new ProductB();
} else {
return null;
}
}
}
Main.java
package com.factory.simple;
public class Main {
public static void main(String args[]) {
Product a = Factory.create("A");
a.printName(); // product A
}
}