设计模式

设计模式

工厂模式生成bean

工厂模式分为静态工厂和实例工厂

静态工厂:

#静态工厂通过静态方法获取实例,实例为静态方法和类初始化一起



public class ClientService {
    private static ClientService clientService = new ClientService();
    private ClientService() {}

    // 静态方法
    public static ClientService createInstance() {
        return clientService;
    }
}

实例工厂

# 实例工厂有专门的工厂类,根据不同工厂方法获取不同的实例类型
# DefaultServiceLocator 为实例工厂类

    






public class DefaultServiceLocator {

    private static ClientService clientService = new ClientServiceImpl();

    private static AccountService accountService = new AccountServiceImpl();

    public ClientService createClientServiceInstance() {
        return clientService;
    }

    public AccountService createAccountServiceInstance() {
        return accountService;
    }
}

你可能感兴趣的:(设计模式)