设计原则之:DIP/依赖反转原则
2021-02-25 本文已影响0人
WorldPeace_hp
Dependncy Inversion Principle\n依赖反转原则:指导如何抽象
定义:
1.高层模块不应该直接依赖底层模块,两者都应该依赖抽象层;
2.抽象不能依赖细节,细节必须依赖抽象。
适用范围:
DIP原则:用于指导如何抽象
DIP原则用于指导抽象出接口或者抽象类。
来个例子看看~~~
《不好的依赖》:
违反了原则Player2直接使用了Ford类对象作为参数。
1.Ford类修改,Player2类《需要》重新编译、测试。
- 有过多重复性代码。
//使用
- (void)noGoodDIP {
DIPPlayer2 *player = [DIPPlayer2 new];
[player play:[DIPFord new]];
[player play1:[DIPBenz new]];
[player play2:[DIPChery new]];
}
@interface DIPPlayer2 : NSObject
- (void)play:(DIPFord *)car; //开福特
- (void)play1:(DIPBenz *)car; //开奔驰
- (void)play2:(DIPChery *)car; //开奇瑞
@end
@implementation DIPPlayer2
- (void)play:(DIPFord *)car {
[car accelerate];
[car shift];
[car steer];
[car brake];
}
- (void)play1:(DIPBenz *)car {
[car accelerate];
[car shift];
[car steer];
[car brake];
}
- (void)play2:(DIPChery *)car {
[car accelerate];
[car shift];
[car steer];
[car brake];
}
@end
《好的依赖》:
对应原则“ DIPPlayer1(高)层模块不直接依赖DIPCar(底)层模块”,Player1依赖Car接口,Ford/Benz/Chery依赖Car接口,不需要知道具体车型。
1.Ford,Benz,Chery类修改,Player1类“不需要”重新编译、测试。
2.不需要过多重复性代码。
// 使用
- (void)goodDIP {
DIPPlayer1 *player = [DIPPlayer1 new];
[player play:[DIPFord new]];
[player play:[DIPBenz new]];
[player play:[DIPChery new]];
}
@interface DIPPlayer1 : NSObject
- (void)play:(id<DIPCar>)car;//开车
@end
@interface DIPPlayer1 : NSObject
- (void)play:(id<DIPCar>)car {
[car accelerate];
[car shift];
[car steer];
[car brake];
}
@end
Car协议:
@protocol DIPCar <NSObject>
- (void)accelerate;//加速
- (void)shift;//换挡
- (void)steer;//转向
- (void)brake;//刹车
@end
福特车实现DIPCar协议:
@interface DIPFord : NSObject <DIPCar>
@end
@implementation DIPFord
- (void)accelerate {NSLog(@"%s",__func__);}//加速
- (void)shift {NSLog(@"%s",__func__);}//换挡
- (void)steer {NSLog(@"%s",__func__);}//转向
- (void)brake {NSLog(@"%s",__func__);}//刹车
@end
奔驰车实现DIPCar协议:
@interface DIPBenz : NSObject <DIPCar>
@end
@implementation DIPBenz
- (void)accelerate {NSLog(@"%s",__func__);}//加速
- (void)shift {NSLog(@"%s",__func__);}//换挡
- (void)steer {NSLog(@"%s",__func__);}//转向
- (void)brake {NSLog(@"%s",__func__);}//刹车
@end
奇瑞车实现DIPCar协议:
@interface DIPChery : NSObject <DIPCar>
@end
@implementation DIPChery
- (void)accelerate {NSLog(@"%s",__func__);} //加速
- (void)shift {NSLog(@"%s",__func__);} //换挡
- (void)steer {NSLog(@"%s",__func__);} //转向
- (void)brake {NSLog(@"%s",__func__);} //刹车
@end