工厂模式
工厂方法模式
//接口
interface Product1
{
void method1();
}
//继承实现
class Product1A implements Product
{
@Override
public void method1() {
System.out.println("ProductA---method1");
}
}
//继承实现
class Product1B implements Product
{
@Override
public void method1() {
System.out.println("ProductB---method1");
}
}
//调用方式
public class FactoryMethod
{
public static void main(String[] args) {
Product product = new Product1A();
product.method1();
}
}
简单工厂模式
//接口
interface Product
{
void method1();
}
//继承实现A
class ProductA implements Product
{
@Override
public void method1() {
System.out.println("ProductA.method1 executed.");
}
}
//继承实现B
class ProductB implements Product
{
@Override
public void method1() {
System.out.println("ProductB.method1 executed.");
}
}
// 简单工厂
class SimpleFactoryIn
{
public static Product createProduct(String type) {
if ("A".equals(type)) {
return new ProductA();
}
else if ("B".equals(type)) {
return new ProductB();
}
return null;
}
}
public class SimpleFactory
{
public static void main(String[] args) {
Product product = SimpleFactoryIn.createProduct("A");
product.method1();
}
}
工厂模式-支持闭包拓展
@Component
public class DynamicFactory
{
private static Map dyFactory = new HashMap<>();
public static void register(String type, ProductInter productInter) {
if (type != null) {
dyFactory.put(type, productInter);
}
}
public static ProductInter getProduct(String type) {
return dyFactory.get(type);
}
}
//接口
public interface ProductInter
{
void method1();
}
//继承实现
@Service
public class ProductImplA implements ProductInter
{
//启动时加入到工程中
@PostConstruct
private void init() {
DynamicFactory.register("productimpla", new ProductImplA());
}
@Override
public void method1() {
System.out.println("ProductA.method1 executed.");
}
}
//继承实现
@Service
public class ProductImplB implements ProductInter
{
@PostConstruct
private void init() {
DynamicFactory.register("productimplb", new ProductImplB());
}
@Override
public void method1() {
System.out.println("ProductB.method1 executed.");
}
}
//测试
@Test
void test() {
//传入对应的初始化名称
ProductInter product = DynamicFactory.getProduct("productimpla");
product.method1();
}