Java多线程 解决private对象逸出-工厂模式(解决对象还未初始化完成就对外暴露)

文章目录

工厂模式

使用工厂模式 ,对象一旦发布就是一个完整的对象,
修复之前如下的文章中, 使用监听器,对象未完成初始化就把对象提供给外界
https://javaweixin6.blog.csdn.net/article/details/108350767

构造方法使用private , 这样其他的对象不能调用构造方法.

创建此工厂方法, 完成了初始化之后, 再进行注册

main方法修改如下 :

完整的代码如下:

package com.thread.background;

/**
 * 类名称:FactoryDesignFixListener
 * 类描述:  工厂模式修复监听器的对象还未初始化完成就对外发布
 *
 * @author: https://javaweixin6.blog.csdn.net/
 * 创建时间:2020/9/2 22:13
 * Version 1.0
 */
public class FactoryDesignFixListener {

    int count;

    private EventListener listener;

    private FactoryDesignFixListener(FactoryDesignFixListener.MySource source) {
        //匿名内部类的方式 , 创建 EventListener接口实例
        listener = new EventListener() {
            @Override
            public void onEvent(Event e) {
                //监听器, 监听到东西的时候, 就打印获取的值
                System.out.println("\n我得到的数字是   " + count);
            }
        };

        //模拟其他业务逻辑
        for (int i = 0; i < 10000; i++) {
            System.out.print(i);
        }

        //count初始化
        count = 100;
    }

    /**
     * 工厂模式方法
     *
     * @param source
     * @return
     */
    public static FactoryDesignFixListener getInstance(MySource source) {
        FactoryDesignFixListener sageListener = new FactoryDesignFixListener(source);

        //完成了初始化之后, 再进行注册
        source.registerListener(sageListener.listener);
        return sageListener;
    }


    public static void main(String[] args) {
        MySource mySource = new MySource();
        new Thread(() -> {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            FactoryDesignFixListener instance = FactoryDesignFixListener.getInstance(mySource);
            mySource.eventCome(new FactoryDesignFixListener.Event() {

            });
        }).start();
        FactoryDesignFixListener instance = FactoryDesignFixListener.getInstance(mySource);
    }

    static class MySource {

        private FactoryDesignFixListener.EventListener listener;

        void registerListener(FactoryDesignFixListener.EventListener eventListener) {
            this.listener = eventListener;
        }

        /**
         * 每次有事件来临的时候, 触发eventCome方法
         *
         * @param e
         */
        void eventCome(FactoryDesignFixListener.Event e) {
            if (listener != null) {
                listener.onEvent(e);
            } else {
                System.out.println("还未初始化完毕!  ");
            }
        }

    }

    interface EventListener {
        void onEvent(FactoryDesignFixListener.Event e);
    }

    interface Event {

    }

}

运行程序打印如下, 得到的是100 . 而之前由于已经隐含的暴露了外部类的对象,得到的是0 .

猜你喜欢

转载自blog.csdn.net/qq_33229669/article/details/108371637