架构设计原则之接口隔离原则

在面向对象编程中,六大设计原则,旨在使软件设计更易于理解、灵活和可维护。这些经验是前人经过多年实践总结的经验。

六大设计原则如下:

· 单一职责原则

· 开闭原则

· 里氏替换原则

· 接口隔离原则

· 依赖反转原则

· 迪米特原则

本文我们来介绍接口隔离原则。

接口隔离原则

接口隔离原则强调的是类或者接口应该尽可能细分,对于业务来说业务应该拆分更小的业务处理。

1.一个类对一类的依赖应该建立在最小的接口之上。

2.建立单一拆分后的接口,不要建立庞大臃肿的接口。

3.尽量细化接口,接口中的方法尽量少(不是越少越好,一定要适度)。

接口隔离原则符合我们常说的高内聚低耦合的设计思想,使框架有更好的可读性、 可扩展性、可维护性。

我们在设计接口的时候,要多花时间去思考业务模型,包括一些需求变更可能性大的业务做一些预判。

抽象不要依赖具体实现细节,具体实现细节依赖抽象,如 接口和衍生类,衍生类应该依赖接口去实现。

在调用链上,调用者和被调用者通过抽象相互依赖,常见有 IOC和DI。

代码示例

以缓存为例,我们要做缓存数据,缓存redis、MemoryCache 要做过时间,XML数据不需要设置缓存时间,应该抽象两个接口:读写缓存、缓存时间接口
interface Cache

{


void SetValue(string key, string value);

void GetValue(string key);

}


interface CacheTime

{

bool ExpiredTime(int sconds);

}


class Redis : Cache, CacheTime

{

public void SetValue(string key, string value)

{

Console.WriteLine("Redis写缓存");

//todo

}

public void GetValue(string key)

{

//todo

Console.WriteLine("Redis取缓存");

}

public bool ExpiredTime(int sconds)

{

Console.WriteLine("Redis设置过期时间");

return true;

}

}


class MemoryCache : Cache, CacheTime

{

public void SetValue(string key, string value)

{

Console.WriteLine("MemoryCache写缓存");

//todo

}

public void GetValue(string key)

{

//todo

Console.WriteLine("MemoryCache取缓存");

}

public bool ExpiredTime(int sconds)

{

Console.WriteLine("MemoryCache设置过期时间");

return true;

}

}


class XMLCache : Cache

{

public void SetValue(string key, string value)

{

Console.WriteLine("XML写缓存");

//todo

}

public void GetValue(string key)

{

//todo

Console.WriteLine("XML取缓存");

}

}



如果把ExpiredTime 方法放在Cache接口中,XMLCache不需要过期时间,继承Cache后也要实现ExpiredTime,这样可伸缩性就会降低。

总结

接口隔离原则帮助我们做可伸缩性和可扩展性的架构,在面向对象编程中,尽量可能的面向接口和抽象类编程。

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章