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

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.

主站蜘蛛池模板: 会东县| 中超| 盐源县| 全南县| 筠连县| 临潭县| 宣武区| 莲花县| 北海市| 类乌齐县| 吐鲁番市| 离岛区| 辽宁省| 瑞昌市| 嘉荫县| 安吉县| 隆尧县| 林周县| 永修县| 东乡族自治县| 吴旗县| 卢氏县| 蓬莱市| 唐山市| 上高县| 峨眉山市| 建德市| 贵南县| 定陶县| 彭阳县| 改则县| 沙洋县| 游戏| 桃江县| 德令哈市| 甘南县| 卢湾区| 南乐县| 灵山县| 南漳县| 都匀市|