欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

工厂模式

程序员文章站 2022-06-01 21:01:32
...
简单工厂模式


// 产品接口
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();
}

}

相关标签: Apple

上一篇: 堆排序

下一篇: 神奇的口袋