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

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.

主站蜘蛛池模板: 同江市| 家居| 阳曲县| 方正县| 长宁县| 自贡市| 辽阳市| 佛山市| 奉新县| 黄平县| 三都| 湖口县| 平武县| 阜康市| 尚义县| 岢岚县| 新干县| 莱芜市| 淮北市| 依兰县| 定州市| 岫岩| 南投市| 青河县| 陕西省| 旺苍县| 三江| 宝山区| 喀喇沁旗| 林周县| 阜南县| 长垣县| 涿鹿县| 江孜县| 上杭县| 平泉县| 全州县| 阳城县| 瑞丽市| 武宁县| 黄龙县|