类图
工厂模式.png结构很简单,一目了然,下面看实际的代码实现。
使用
调用
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Product one = new FactoryA().createProducte();
one.printInformation();
Product two = new FactoryB().createProducte();
two.printInformation();
}
}
输出
这是A产品
这是B产品
Process finished with exit code 0
产品接口
package com.company;
public interface Product {
void printInformation();
}
A产品
package com.company;
public class ProductA implements Product {
@Override
public void printInformation() {
System.out.println("这是A产品");
}
}
B产品
package com.company;
public class ProductB implements Product {
@Override
public void printInformation() {
System.out.println("这是B产品");
}
}
工厂接口
package com.company;
public interface Factory {
/**
* 根据字符串选择具体的工厂
* @return
*/
Product createProducte();
}
A工厂
package com.company;
public class FactoryA implements Factory {
@Override
public Product createProducte() {
return new ProductA();
}
}
B工厂
package com.company;
public class FactoryB implements Factory {
@Override
public Product createProducte() {
return new ProductB();
}
}
网友评论