设计模式六大原则
定义:简称ISP。客户端不应该依赖它不需要的接口;一个类对另一个类的依赖应该建立在最小的接口上。
举例子:
给出指定食材(西红柿、黄瓜、芹菜),冷热菜师傅要根据自己的需求不同,对食材进行预处理。
先看不使用接口隔离原则,代码会什么样:
public class MadeFood {
interface MadeFoodInter{
void madeHot();
void madeCold();
}
class Tomatoes implements MadeFoodInter{
@Override
public void madeHot() {
Log.w("打印","热菜->打鸡蛋->翻炒->西红柿炒鸡蛋");
}
@Override
public void madeCold() {
Log.w("打印","冷菜->切片->加糖->搅拌->糖拌柿子");
}
}
class Cucumber implements MadeFoodInter{
@Override
public void madeHot() {
Log.w("打印","热菜->切肉->翻炒->黄瓜炒肉");
}
@Override
public void madeCold() {
Log.w("打印","冷菜->拍碎->加调料->搅拌->拍黄瓜");
}
}
class Celery implements MadeFoodInter{
@Override
public void madeHot() {
Log.w("打印","热菜->切段->炒肉->加芹菜->芹菜炒肉");
}
@Override
public void madeCold() {
Log.w("打印","冷菜->切段->焯水->加调料->凉拌芹菜");
}
}
public MadeFoodInter getMade(String name){
MadeFoodInter madeFoodInter = null;
if(name.equals("西红柿")){
madeFoodInter = new Tomatoes();
}else if(name.equals("黄瓜")){
madeFoodInter = new Cucumber();
}else if(name.equals("芹菜")){
madeFoodInter = new Celery();
}
return madeFoodInter;
}
}
从上面的例子能看出来,把冷热菜需要的功能放到一个接口里之后,当热菜师傅调用接口之后,冷菜的制作方法也强制摆在热菜师傅面前,这显然是我们不应该设计出来的。
下面进行调整:
public class MadeFood {
interface MadeHotInter{
void madeHot();
}
interface MadeColdInter{
void madeCold();
}
class Tomatoes implements MadeHotInter,MadeColdInter{
@Override
public void madeHot() {
Log.w("打印","热菜->打鸡蛋->翻炒->西红柿炒鸡蛋");
}
@Override
public void madeCold() {
Log.w("打印","冷菜->切片->加糖->搅拌->糖拌柿子");
}
}
class Cucumber implements MadeHotInter,MadeColdInter{
@Override
public void madeHot() {
Log.w("打印","热菜->切肉->翻炒->黄瓜炒肉");
}
@Override
public void madeCold() {
Log.w("打印","冷菜->拍碎->加调料->搅拌->拍黄瓜");
}
}
class Celery implements MadeHotInter,MadeColdInter{
@Override
public void madeHot() {
Log.w("打印","热菜->切段->炒肉->加芹菜->芹菜炒肉");
}
@Override
public void madeCold() {
Log.w("打印","冷菜->切段->焯水->加调料->凉拌芹菜");
}
}
public MadeHotInter getHote(String name){
MadeHotInter madeFoodInter = null;
if(name.equals("西红柿")){
madeFoodInter = new Tomatoes();
}else if(name.equals("黄瓜")){
madeFoodInter = new Cucumber();
}else if(name.equals("芹菜")){
madeFoodInter = new Celery();
}
return madeFoodInter;
}
public MadeColdInter getColde(String name){
MadeColdInter madeFoodInter = null;
if(name.equals("西红柿")){
madeFoodInter = new Tomatoes();
}else if(name.equals("黄瓜")){
madeFoodInter = new Cucumber();
}else if(name.equals("芹菜")){
madeFoodInter = new Celery();
}
return madeFoodInter;
}
}
这里当然也可以对代码进行简化,但是这样更加直观。这样处理之后热菜师傅拿到的都是热菜的制作方法,冷菜师傅拿到的也只是冷菜的制作方法。调用此方法代码量不一定会减少,但逻辑会变清晰。
总之:接口隔离原则就是尽量让接口内的方法都是调用时必用的,原则上宁可接口多,也不要功能杂(当然也要根据开发实际情况)。