官术网_书友最值得收藏!

Interface Segregation Principle

The Interface Segregation Principle states that:

No client should be forced to depend on methods it does not use.

According to this principle, if an interface has too many methods, then we need to divide the interface into smaller interfaces with fewer methods. A simple example of this principle is shown next.

Let us assume we are using a custom interface to detect various states of a view:

public interface ClickListener { 
   public void onItemClickListener(View v, int pos); 
   public void onItemLongClickListener(View v, int pos); 
   public void onItemPressListener(View v, int pos); 
   public void onSelectedListener(View v, int pos); 
} 

Now, while implementing this listener, we only want the onItemClickListener or the onItemLongClickListener; the others are not required but we still have to use them in the code. This violates the Interface Segregation Principle.

Now we can easily resolve this by splitting the interface into smaller interfaces, like this:

public interface ClickListener { 
   public void onItemClickListener(View v, int pos); 
   public void onItemLongClickListener(View v, int pos); 
} 
public interface HoldListener { 
   public void onItemPressListener(View v, int pos); 
   public void onSelectedListener(View v, int pos); 
} 

Now we will only initialize the ClickListener and use its methods instead of the old interface where we had to utilize four methods. Here we have segregated them into two different interfaces.

主站蜘蛛池模板: 新平| 壶关县| 邓州市| 商都县| 呼伦贝尔市| 丰顺县| 闵行区| 东宁县| 丰县| 特克斯县| 沾益县| 水城县| 诏安县| 巴彦县| 吐鲁番市| 宣威市| 临沭县| 柘荣县| 大兴区| 珠海市| 罗城| 延吉市| 康乐县| 利津县| 鄯善县| 金溪县| 芦山县| 呼和浩特市| 兴安县| 中西区| 永丰县| 清新县| 康乐县| 永胜县| 墨江| 吉木乃县| 襄垣县| 犍为县| 洛浦县| 富民县| 荔浦县|