1.简单工厂模式
public abstract Fruit {
public abstract void printName();
}
public class Apple extends Fruit {
public Apple() {
}
public void printName() {
System.out.println("this is an apple");
}
}
public class Orange {
public Orange() {
}
public void printName() {
System.out.println("this is an orange");
}
}
public class ProduceFactory {
public Fruit produce(String name) {
if ("apple".equals(name)) {
return new Apple();
}
if ("orange".equals(name)) {
return new Orange();
}
return null;
}
}
2.抽象工厂模式
public abstract class Fruit {
public abstract void print();
}
public Apple extends Fruit {
public Apple() {
}
public void print() {
System.out.println("this is an apple");
}
}
public Orange extends Fruit {
public Orange() {
}
public void print() {
System.out.println("this is an Orange");
}
}
public abstract class Product {
public Fruit produce(Class class);
}
public class FruitProduct extends Product {
public Fruit produce(Class class) {
Fruit fruit = null;
try {
fruit = (Fruit) Class.forName(class.getName()).newInstance();
} catch (Exception e) {
e.printStackStrace();
}
return fruit;
}
}