【二三方】_工厂模式在三方业务中的应用

工厂模式在三方业务中的应用

  • 1.先创建一个接口,后续的工厂对象都是该接口的实现类对象:

    1
    2
    3
    public interface HelloService {
    void hello(String hello);
    }
  • 2.创建一些实现接口的实现类,分别实现抽象方法使其具有不同的功能,然后将他们放入Spring容器中,并赋上不同的name,这样Spring中就具有Class相同而name不同的bean:

    1
    2
    3
    4
    5
    6
    7
    @Component("chinese")
    public class ChineseHelloServiceImpl implements HelloService {
    @Override
    public void hello(String hello) {
    System.out.println("你好!" + hello);
    }
    }
    1
    2
    3
    4
    5
    6
    7
    @Component("english")
    public class EnglishHelloServiceImpl implements HelloService {
    @Override
    public void hello(String hello) {
    System.out.println("hi!hello!" + hello);
    }
    }
  • 3.在一个bean中通过Map<String,HelloService>进行依赖注入,则会将Spring容器中所有继承了HelloService接口的bean都注入到该map中,其中key为name,value为bean。那么我们就可以在已知name的情况下通过map的get方法获得bean,从而实现工厂模式:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @Service
    public class HelloFactory {

    @Autowired
    Map<String,HelloService> map;

    public HelloService getBean(String beanName) {
    return map.get(beanName);
    }
    }
  • 4.创建一个方法使用Factory类对象:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @Service
    public class SayHello {

    @Autowired
    HelloFactory helloFactory;

    public void sayHello(String beanName,String hello) {
    helloService helloService = helloFactory.getBean(beanName);
    helloService.hello(hello);
    }
    }