3
Its generally not a good practice to load up your AppDelegate as a container for app-wide variables in this way. It can quickly get unwieldy.
以这种方式将AppDelegate作为应用程序范围变量的容器加载通常不是一个好习惯。它很快就会变得笨拙。
A common practice is to define some singleton objects, as follows:
通常的做法是定义一些单例对象,如下所示:
+ (instancetype)shared
{
static dispatch_once_t onceToken;
static MyServiceClient* instance;
dispatch_once(&onceToken, ^ //Use GCD to make a singleton with thread-safety
{
instance = [[self alloc] init];
});
return instance;
}
You can then provide these objects as parameters to your classes that require them as collaborators.
然后,您可以将这些对象作为参数提供给需要它们作为协作者的类。
Use Dependency Injection
使用依赖注入
Note though that singleton can be considered an anti-pattern. If you inject these singletons into classes that require them its not too bad, however it's definitely not recommend to hard-wire them (unfortunately, also a common practice), as this promotes too-tight coupling, cohesion and requires complicated swizzling in order perform unit tests.
请注意,单例可以被视为反模式。如果你将这些单体注入需要它们的类别并不太糟糕,但绝对不建议硬连线(不幸的是,这也是一种常见的做法),因为这会促进过于紧密的耦合,凝聚力并需要复杂的调配才能执行单元测试。
Another approach is to use dependency injection, in which case the objects need not even be singletons, in most cases. You can instantiate an object-graph of collaborating components for a given use-case that will come and go as needed. This has the benefit of using less memory on resource constrained devices.
另一种方法是使用依赖注入,在这种情况下,在大多数情况下,对象甚至不需要是单例。您可以根据需要实例化给定用例的协作组件的对象图。这样做的好处是可以在资源受限的设备上使用更少的内存。
Its a common misconception that you need a library to use dependency injection. You don't. It can help though. I created a dependency injection container called Typhoon.
它是一个常见的误解,你需要一个库来使用依赖注入。你没有。它可以帮助。我创建了一个名为Typhoon的依赖注入容器。
Notifications
Another way of achieving loose collaboration between classes is to use notifications.
在类之间实现松散协作的另一种方法是使用通知。