设计模式

6大设计原则(SOLID+迪米特法则)

1.单一职责原则(SRP Single Responsibility Principle)

定义:应该有且仅有一个原因引起类的变更。

※接口一定要做到单一职责,类的设计尽量做到只有一个原因引起变化。

※方法的颗粒度要细,职责清晰、单一。

【设计接口时,用户信息抽取为业务对象(用户属性)和业务逻辑(用户行为)】

 

2.开闭原则(OCP Open-Closed Principle)

定义:软件中的对象对扩展开放,对修改关闭。

※尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码。

 

3.里氏替换原则(LSP Liskov Substitution Principle)

定义:所有引用基类的地方必须能透明的使用子类的对象。【增强程序健壮性】

4.接口隔离原则(ISP Interface Segregation Principle)

※接口尽量细化,剔除不需要的接口。

 

5.依赖倒置原则(DIP Dependence Inversion Principle)

※面向接口编程

 

6.迪米特法则/最少知识原则(LOD/LKP Law of Demeter/Least Knowledge Principle)

※一个类公开的public属性和方法越多,修改时涉及的面就越大,变更引起的风险扩散也就越大。

【封装!】

21种设计模式

1.单例模式

单例模式是在实际项目开发中用到比较多的一种设计模式,设计原理是整个系统只产生一个对象实例,通过一个统一的方法对外提供这个实例给外部使用。

单例模式实现:

#import <Foundation/Foundation.h>  
  
@interface Singleton : NSObject  
  
+(instancetype) shareInstance ;  
  
@end  
#import "Singleton.h" @implementation Singleton static Singleton* _instance = nil; +(instancetype) shareInstance { static dispatch_once_t onceToken ; dispatch_once(&onceToken, ^{ _instance = [[super allocWithZone:NULL] init] ; }) ; //GCD方式实现单次访问 return _instance ; } +(id) allocWithZone:(struct _NSZone *)zone { return [Singleton shareInstance] ; } -(id) copyWithZone:(struct _NSZone *)zone { return [Singleton shareInstance] ; } @end

覆盖allocWithZone:和copyWithZone:方法,防止通过alloc和init以及copy来构造对象。

(instancetype与id比较)

posted @ 2016-03-12 00:00  小天sean  阅读(101)  评论(0)    收藏  举报