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

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.

主站蜘蛛池模板: 商南县| 宣恩县| 阳朔县| 黑水县| 江永县| 米林县| 闽侯县| 新河县| 冷水江市| 开封县| 昔阳县| 柳州市| 安新县| 九龙坡区| 博野县| 邓州市| 临城县| 利津县| 壶关县| 新乡市| 石渠县| 舒城县| 南溪县| 西乌| 衡山县| 刚察县| 绥中县| 项城市| 临安市| 西安市| 洱源县| 香港| 宜春市| 徐闻县| 广汉市| 西乡县| 武定县| 都兰县| 贵南县| 上林县| 浮山县|