设计原则之最少知道原则

只与你直接的朋友通信,避免和陌生人通信。


定义:一个对象应该对其他对象保持最少的了解。

问题由来:类与类之间的关系越密切,耦合度越大,当一个类发生改变时,对另一个类的影响也越大。

解决方案:尽量降低类与类之间的耦合。

通俗的来讲,就是一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类来说,无论逻辑多么复杂,都尽量地的将逻辑封装在类的内部,对外除了提供的public方法,不对外泄漏任何信息。迪米特法则还有一个更简单的定义:只与直接的朋友通信。首先来解释一下什么是直接的朋友:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间是朋友关系。耦合的方式很多,依赖、关联、组合、聚合等。其中,我们称出现成员变量、方法参数、方法返回值中的类为直接的朋友,而出现在局部变量中的类则不是直接的朋友。也就是说,陌生的类最好不要作为局部变量的形式出现在类的内部。


形象一点的比喻类似于:监狱内的犯人是不应该跟外面的人接触的,当然或许会有探亲的。这里的监狱就是类,里面的犯人就是类内部的信息,而监狱里的狱警就相当于迪米特法则的执行者。

Family.h

@interface Family : NSObject
-(void)visitPrisoner:(id)aPrisoner;
@end

Family.m

#import "Family.h"
#import "Prisoners.h"
@implementation Family
-(void)visitPrisoner:(Prisoners *)aPrisoner
{
    NSLog(@"family say");
    [aPrisoner helpEachOther];
}

@end

Prisoners.h

#import "Inmates.h"
@interface Prisoners : NSObject
-(void)helpEachOther;

@end

Prisoners.m

#import "Prisoners.h"

@implementation Prisoners
-(void)helpEachOther
{
    NSLog(@"Should help each other between prisoners and prisoners");
    [[[Inmates alloc]init] weAreFriend];
}
@end

Inmates.h

@interface Inmates : NSObject
-(void)weAreFriend;
@end

Inmates.m

#import "Inmates.h"

@implementation Inmates
-(void)weAreFriend
{
    NSLog(@"we are friend");
}
@end

AppDelegate.m

    Family *f = [[Family alloc]init];
    [f visitPrisoner:[[Prisoners alloc]init]];
原文地址:https://www.cnblogs.com/huen/p/3522567.html