SpringBoot 结合工厂模式开发实战

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u010979642/article/details/97653583

SpringUtils

@Component
public class SpringUtils implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(@Nullable ApplicationContext applicationContext) t

单例模式跟工厂模式结合。。

08-18

public abstract class DAOFactory rn [color=#FF0000]//这个构造器添加了就会报错rn private DAOFactory()rn rn [/color]rn private static Object initLock = new Object();rnrn private static DAOFactory factory = null;rnrn //开发模式: 工厂模式Factory、单例模式singletonrn rn public static DAOFactory getInstance() rn if (factory == null) rn synchronized (initLock) rn if (factory == null) rn try rn rn //ConfigurationStaticFinal_app.DBType作用就是从配置中读取选用的方案,接着根据方案创建不同的实例rn //DAOFactoryJDBC4MySQL就是用来返回DAO实例的rn String DBType=ConfigurationStaticFinal_app.DBType;rn if(DBType.equals("MySQL"))rn factory = DAOFactoryJDBC4MySQL.getInstances();rn rn if(DBType.equals("Oracle"))rn factory = new DAOFactoryJDBC4Oracle().getInstances();rn rn rn rn catch (Exception e) rn e.printStackTrace();rn return null;rn rn rn rn rn return factory;rn rn rn------------------------------------------------------------------------------------------------------rn下面是rnDAOFactoryJDBC4MySQL();rnpublic class DAOFactoryJDBC4MySQL extends DAOFactoryrn private DAOFactoryJDBC4MySQL()rn rn rn public static DAOFactoryJDBC4MySQL getInstances()rn return new DAOFactoryJDBC4MySQL();rn rn public UserDAO createUserDAO() rn return new UserDAOImplJDBC4MySQL();rn rn rnrn这里有个问题。。rn如果没private构造器,依然可以通过new关键字去创建该类。。rn但是如果使用了private构造器,子类继承的时候就会出问题了(因为必须调用一次父类的构造器但是设置了private就不可调用了。)rn想问下大家有没什么解决的办法。。可以让DAOFactory跟他的子类都只能通过静态方法去返回他的实例,而不能在外部调用直接New?rn本人还在学习当中,对于实际的开发不了解,想问下大家在实际当中,有没必要规定构造器是私有的?如果可以通过外部new出instance的话这样就算是单例了吧? 论坛

没有更多推荐了,返回首页