Example resolution using singleton patterns in design patterns is used in iOS App development

  • 2020-06-01 11:04:45
  • OfStack

1. The role of singletons
As the name implies, singleton means that the object of this class can only be initialized once in the whole project. This feature can be widely used in some resources that need to be Shared globally, such as management classes and engine classes, and can also be passed through singletons. UIApplication, NSUserDefaults, and so on are system singletons in IOS.

2. Two ways of writing singleton pattern
1. Common writing method


#import "LGManagerCenter.h"

static LGManagerCenter *managerCenter;

@implementation LGManagerCenter

+(LGManagerCenter *)sharedManager{
  if(!managerCenter)
    managerCenter=[[self allocWithZone:NULL] init];
  return managerCenter;
}

@end

2, create the singleton class with GCD


#import "LGManagerCenter.h"


@implementation LGManagerCenter


+(LGManagerCenter *)sharedManager{
  static dispatch_once_t predicate;
  static LGManagerCenter * managerCenter;
  dispatch_once(&predicate, ^{
    managerCenter=[[LGManagerCenter alloc] init];
  });
  return managerCenter;
}

@end

The dispatch_once function is executed only once.

3. Code optimization
Through the above methods, we have been able to use class method to get the singleton, but in many cases, project quantity is large, they may also many developers to participate in the development of a project at the same time, for safety and management code convenience, but also to give not the creator of the singleton but will use this singleton developer 1 some hints, we usually rewrite 1 some methods:

First, we implement an alloc method by ourselves:


+(instancetype)myAlloc{
  return [super allocWithZone:nil];
}

Modify our singleton implementation method slightly:


+(ZYHPayManager *)sharedMamager{
  static ZYHPayManager * manager;
  if (manager==nil) {
    manager=[[ZYHPayManager myAlloc]init];
  }
  return manager;
}

Rewrite the methods of instantiating objects in 1 view:


+(instancetype)alloc{
  NSAssert(0, @" This is a 1 Singleton object, please use +(ZYHPayManager *)sharedMamager methods ");
  return nil;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
  return [self alloc];
}
-(id)copy{
  NSLog(@" This is a 1 A singleton object, copy It won't work ");
  return self;
}
+(instancetype)new{
  return [self alloc];
}

Note: alloc here USES assertions to break up the section where any view creates objects through alloc to give the programmer a hint. The copy method simply returns the original object without any processing, printing the message to the programmer.


Related articles: