Say goodbye to 重复代码---Eclipse代码模板的使用

我们在开发过程中,有些代码是经常重复编写的,而且是必要的,如单例模式,观察者模式.

每次都是重复重复再重复.

那么如何提高我们的效率呢?

要记住,我们使用的是IDE,不是文本编辑器.善用工具,事半功倍!

 

今天就先写一部分如何快速编写单例的代码模板.之后再补上观察者等其他的...之后也会对参数逐个介绍.

 

1.Eclipse中点击Windows-Preferences-Java-Editor-Templates进入到具体的设置页面.

2.点击New打开模板窗口

3.在Name输入框中输入这个模板名,个人这边命名为 : Instance

4.在Description加入模板的描述(非必填),个人这边填写的是 : 非线程安全的单例

5.在Pattern中加入模板代码,以下是单例

private static ${enclosing_type} sInstance;

private ${enclosing_type}() {
}

public static ${enclosing_type} getInstance() {
    if (sInstance == null) {
        sInstance = new ${enclosing_type}();
    }
    return sInstance;
}

注:enclosing_type代表类名

 

OK,配置好了完以上的模板.接下来的使用就很简单了!

1.创建一个新的类.

2.在类中按Alt+/,选择Instance.

0秒写单例!绝对赞!

 

更高效地开发,等着大家一起去探索!

 


 

补,"接口的注册与反注册"模板:

private ArrayList<${name}> mListenerList = new ArrayList<${name}>();
public void registListener(${name} listener) {
    if (!mListenerList.contains(listener)) {
        mListenerList.add(listener);
    }
}

public void unRegistListener(${name} listener) {
    if (mListenerList.contains(listener)) {
        mListenerList.remove(listener);
    }
}

 

posted @ 2014-11-19 14:27  benhero  阅读(847)  评论(0编辑  收藏  举报