手写EventBus框架——动手_整体架构设计

路漫漫其修远兮

01. 手写EventBus框架——源码分析1
02. 手写EventBus框架——源码分析2
03. 手写EventBus框架——动手_整体架构设计
04. 手写EventBus框架——动手_终结


o.O前戏已经足够了,接下来撸     代码了。

主体框架

类设计

第一版结构

EventBus.class

/**
 * <p/>
 * Author: 温利东 on 2017/3/26 10:44.
 * blog: http://www.jianshu.com/u/99f514ea81b3
 * github: https://github.com/LidongWen
 */

public class EventBus {
    private static EventBus ourInstance;

    private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> cacheMap;
    private final Map<Object, List<Class<?>>> typesBySubscriber;
    //粘性
    private final Map<Class<?>, Object> stickyEvents;

    public static EventBus getDefault() {
        if (ourInstance == null) {
            synchronized (EventBus.class) {
                if (ourInstance == null) {
                    ourInstance = new EventBus();
                }
            }
        }
        return ourInstance;
    }

    private EventBus() {
        //初始化一些数据
        cacheMap = new HashMap<>();
        stickyEvents = new ConcurrentHashMap<>();
        typesBySubscriber=new HashMap<>();
    }

    public void register(Object subscriber) {
        //1.找到所有方法
        //2.保存订阅  subscriber();
    }

    public void unRegister(Object subscriber) {
        //去除订阅
    }
    public void post(Object obj) {
        //1.获取缓存 进行判断
        //2.指定线程执行
    }
    public void postSticky(Object obj){
        //加入粘性缓存 stickyEvents
        //执行
    }

    /**
     *  保存订阅方法
     * @param subscriber
     */
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //1.保存数据  ,  如果重复 抛异常
        //2.执行粘性事件
    }
}

线程枚举类

public enum ThreadMode {

    POSTING,

    MAIN,

    BACKGROUND,

    ASYNC
}

注解类

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Subscribe {
    ThreadMode threadMode() default ThreadMode.POSTING;
    //粘性
    boolean sticky() default false;
    //优先级
    int priority() default 0;
}

订阅元元素类 SubscriberMethod ;

/**
 * <p/>
 * Author: 温利东 on 2017/3/23 17:56.
 * blog: http://blog.csdn.net/sinat_15877283
 * github: https://github.com/LidongWen
 */

public class SubscriberMethod {
    final Method method;
    final ThreadMode threadMode;
    final Class<?> eventType;       //参数
    final int priority;
    final boolean sticky;
    /**
     * Used for efficient comparison
     */
    String methodString;

    public SubscriberMethod( Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky) {
        this.method = method;
        this.threadMode = threadMode;
        this.eventType = eventType;
        this.priority = priority;
        this.sticky = sticky;
    }

    @Override
    public boolean equals(Object other) {
        if (other == this) {
            return true;
        } else if (other instanceof SubscriberMethod) {
            checkMethodString();
            SubscriberMethod otherSubscriberMethod = (SubscriberMethod) other;
            otherSubscriberMethod.checkMethodString();
            // Don't use method.equals because of http://code.google.com/p/android/issues/detail?id=7811#c6
            return methodString.equals(otherSubscriberMethod.methodString);
        } else {
            return false;
        }
    }

    private synchronized void checkMethodString() {
        if (methodString == null) {
            // Method.toString has more overhead, just take relevant parts of the method
            StringBuilder builder = new StringBuilder(64);
            builder.append(method.getDeclaringClass().getName());
            builder.append('#').append(method.getName());
            builder.append('(').append(eventType.getName());
            methodString = builder.toString();
        }
    }

    @Override
    public int hashCode() {
        return method.hashCode();
    }
}

扩展框架设计_01

以上整体的一个架构就出来了,可以看出来,整体的逻辑都在EventBus类里面,虽然其中都是些伪代码,但代码量还是很大的,那么我们可以抽出一些伪代码作为帮助类;

  1. 订阅方法查找类;SubscriberMethodFinder.class;
  2. 方法执行帮助类; InvokeHelper.class;

那么结构就变成这样了


InvokeHelper.class

/**
 *  方法执行帮助类
 * <p/>
 * Author: 温利东 on 2017/3/26 11:29.
 * blog: http://www.jianshu.com/u/99f514ea81b3
 * github: https://github.com/LidongWen
 */
public class InvokeHelper {

    public static void post(SubscriberMethod subscriberMethod,Object event, boolean isMainThread) {
        switch (subscriberMethod.threadMode) {
            case POSTING:
                //直接执行
                break;
            case MAIN:
                if (isMainThread) {
                    //直接执行
                } else {
                    // 放在handler内执行
                }
                break;
            case BACKGROUND:
                if (isMainThread) {
                    //放在后台线程执行
                } else {
                    //执行
                }
                break;
            case ASYNC:
                //放在异步线程内执行
                break;
            default:
                //抛异常
                throw new IllegalStateException("Unknown thread mode: " + subscriberMethod.threadMode);
        }
    }
}

SubscriberMethodFinder.class

/**
 *  订阅方法查找类
 * <p/>
 * Author: 温利东 on 2017/3/26 11:21.
 * blog: http://www.jianshu.com/u/99f514ea81b3
 * github: https://github.com/LidongWen
 */
public class SubscriberMethodFinder {
    private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

    /**
     * 查找方法
     * @param subscriberClass
     * @return
     */
    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        return null;
    }
}

扩展框架设计_02

  1. 异步线程 AsyncPoster
  2. 顺序执行BackgroundPoster

这下子架构就变成这样了


/**
 * //异步线程
 * <p/>
 * Author: 温利东 on 2017/3/26 17:36.
 * blog: http://www.jianshu.com/u/99f514ea81b3
 * github: https://github.com/LidongWen
 */
public class AsyncPoster implements Runnable {
    @Override
    public void run() {

    }
}
/**
 * Posts events in background.
 * <p/>
 * Author: 温利东 on 2017/3/26 17:36.
 * blog: http://www.jianshu.com/u/99f514ea81b3
 * github: https://github.com/LidongWen
 */
final class BackgroundPoster implements Runnable {


    @Override
    public void run() {

    }

}

还漏了一个 Subscription.class 这里加上

Subscription.class

final class Subscription {
    final Object subscriber;
    final SubscriberMethod subscriberMethod;

    volatile boolean active;

    Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
        this.subscriber = subscriber;
        this.subscriberMethod = subscriberMethod;
        active = true;
    }

    @Override
    public boolean equals(Object other) {
        if (other instanceof Subscription) {
            Subscription otherSubscription = (Subscription) other;
            return subscriber == otherSubscription.subscriber
                    && subscriberMethod.equals(otherSubscription.subscriberMethod);
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return subscriber.hashCode() + subscriberMethod.methodString.hashCode();
    }
}

好了 现在我们简易版EventBus框架结构就搭建起来了。其中没有实现代码,全是伪代码逻辑。其实写到这里,各位都可以自己敲代码来实现具体的功能了。

下一节我们将完成以及完善我们简易版EventBus的功能了。

下一节: 04. 手写EventBus框架——动手_终结


希望我的文章不会误导在观看的你,如果有异议的地方欢迎讨论和指正。
如果能给观看的你带来收获,那就是最好不过了。

人生得意须尽欢, 桃花坞里桃花庵
点个关注呗,对,不信你点试试?
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容