简单工厂模式
工厂方法模式
抽象工厂模式
// 产品接口
public interface Product {
public void getName();
}
// 具体产品A
public class ProductA implements Product {
public void getName() {
System.out.println(" I am ProductA ");
}
}
// 具体产品B
public class ProductB implements Product {
public void getName() {
System.out.println(" I am ProductB ");
}
}
// 工厂类
public class ProductCreator {
public Product createProduct(String type) {
if (" A ".equals(type)) {
return new ProductA();
}
if (" B ".equals(type)) {
return new ProductB();
} else
return null;
}
public static void main(String[] args) {
ProductCreator creator = new ProductCreator();
creator.createProduct(" A ").getName();
creator.createProduct(" B ").getName();
}
}
工厂方法模式
public interface Factory
{
Apple createApple();
}
public class ConcreteFactory1 implements Factory
{
public Apple createApple()
{
return new RedApple();
}
}
public class ConcreteFactory2 implements Factory
{
public Apple createApple()
{
return new GreenApple();
}
}
抽象工厂模式
public interface Factory
{
Apple createApple();
Grape createGrape();
}
public class ConcreteFactory1 implements Factory
{
public Apple createApple()
{
return new RedApple();
}
public Grape createGrape()
{
return new RedGrape();
}
}
public class ConcreteFactory2 implements Factory
{
public Apple createApple()
{
return new GreenApple();
}
public Grape createGrape()
{
return new GreenGrape();
}
}