1 public class A { 2 public static void main(String[] args) { 3 Factory factory = newFactory(); 4 System.out.println(factory.productString("蔬菜")); 5 System.out.println(factory.productString("米饭")); 6 System.out.println(factory.productInteger("一")); 7 System.out.println(factory.productInteger("五")); 8 } 9 } 10 11 public class Factory { 12 public String productString(String inputStr) { 13 if (inputStr.equals("水果")) 14 return "生产的水果"; 15 if (inputStr.equals("蔬菜")) 16 return "生产的蔬菜"; 17 return "请输入正确需求"; 18 } 19 20 public Integer productInteger(String inputStr) { 21 if (inputStr.equals("一")) 22 return 1; 23 if (inputStr.equals("二")) 24 return 2; 25 return 0; 26 } 27 } 28
1 //抽象产品类 2 abstract class Product{ 3 public abstract void show(); 4 } 5 //A产品 6 class ProductA extends Product{ 7 public void show(){ 8 System.out.println("这是A产品"); 9 } 10 } 11 //B产品 12 class ProductB extends Product{ 13 public void show(){ 14 System.out.println("这是B产品"); 15 } 16 } 17 //抽象工厂类 18 abstract class Factory{ 19 public abstract Product manuPro(); 20 } 21 //A工厂 22 class FactoryA extends Factory{ 23 public Product manuPro(){ 24 return new ProductA(); 25 } 26 } 27 //B工厂 28 class FactoryB extends Factory{ 29 public Product manuPro(){ 30 return new ProductB(); 31 } 32 } 33 34 //主类 35 public class Main{ 36 //A工厂生产A产品 37 FactoryA factoryA=new FactoryA(); 38 Product product=factoryA.manuPro(); 39 product.show();//"这是A产品" 40 //B工厂生产B产品 41 FactoryB factoryB=new FactoryB(); 42 product=factoryB.manuPro(); 43 product.show();//"这是B产品" 44 }
原文:https://www.cnblogs.com/afei1759/p/11056057.html