SoFunction
Updated on 2025-04-12

Detailed explanation of the application of Xiangyuan mode in iOS App design model development

The concept of the Enjoyment Model

In object-oriented software design, utilizing public objects can not only save resources but also improve performance. A shared object can only provide some inherent information and cannot be used to identify an object. A design pattern specifically used to design shareable objects is called Flyweight pattern.

Implementing the Encoding pattern requires two key components, usually shareable Encoding objects and the pool that saves them. Some kind of central object maintains this pool and returns the appropriate instance from it.
Use sharing technology to effectively support a large number of fine-grained objects.

Public transportation (such as buses) has been around for more than a hundred years. A large number of passengers heading to the same direction can share the cost of owning and operating vehicles (such as buses). The bus has multiple platforms and passengers get on and off along the route near their destination. The cost of arriving at the destination is only related to the itinerary. It is much cheaper to take a bus than to keep a vehicle. This is the benefit of utilizing public resources.

In object-oriented software design, we use public objects to not only save resources but also improve performance. For example, a character needs one million instances of a class, but we can share an instance of this class with everyone, and put some unique information outside, and the savings may be considerable (the difference between one instance and one million instances). Shared objects only provide some inherent information and cannot be used to identify objects. A design pattern specifically used to design shareable objects is called the Encyclopedia Mode.

What is the most important reason why the Xiangyuan object is lightweight? It is not their size, but the total amount of space that can be saved by sharing. The unique state of certain objects can be taken externally, managed elsewhere, and the rest are shared. For example, one million objects of a class were originally needed, but because the object of this class is for the enjoyment, now only one is enough. This is why the shared-enriched object makes the entire system lightweight. Through careful design, the memory savings are considerable. In iOS development, saving memory means improving overall performance.


Example application of Xiangyuan mode

We create a WebSiteFactory factory class to maintain the extrinsic objects in the pool, and return the specific extrinsic objects of various types according to the parent type. The code is as follows:

Copy the codeThe code is as follows:

#import <Foundation/>
#import ""
@interface WebSiteFactory : NSObject
 
@property (nonatomic, strong) NSDictionary *flyweights; //Shared object
 
- (id<WebSiteProtocol>)getWebSiteCategory:(NSString *)webKey;
- (NSInteger)getWebSiteCount;
 
@end

Copy the codeThe code is as follows:

#import ""
#import ""
@implementation WebSiteFactory
 
- (instancetype)init {
    self = [super init];
    if (self) {
        _flyweights = [NSDictionary dictionary];
    }
    return self;
}
 
- (id<WebSiteProtocol>)getWebSiteCategory:(NSString *)webKey {   
    __block id<WebSiteProtocol> webset = nil;
    [ enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if (webKey == key) {
            webset = obj;
            *stop = YES;
        }
    }];
    
    if (webset == nil) {
        ConcreteWebSite *concreteWebset = [[ConcreteWebSite alloc] init];
        = webKey;
        webset = concreteWebset;
        
        NSMutableDictionary *mutabledic = [NSMutableDictionary dictionaryWithDictionary:];
        [mutabledic setObject:webset forKey:webKey];
        = [NSDictionary dictionaryWithDictionary:mutabledic];
    }
    
    return webset;
}
 
- (NSInteger)getWebSiteCount {
    return ;
}
 
@end

The getWebSiteCategory method in the code can return a specific extant object. The returned extant object also complies with the WebSiteProtocol protocol. The code of the WebSiteProtocol is as follows:
Copy the codeThe code is as follows:

#import <Foundation/>
#import ""
@protocol WebSiteProtocol <NSObject>
 
- (void)use:(User *)user;
 
@end

The code of ConcreteWebSite is as follows:
Copy the codeThe code is as follows:

#import <Foundation/>
#import ""
@interface ConcreteWebSite : NSObject <WebSiteProtocol>
 
@property (nonatomic, copy) NSString *webName;
 
@end

Copy the codeThe code is as follows:

#import ""
 
@implementation ConcreteWebSite
 
- (void)use:(User *)user {
NSLog(@"Website category:%@ User name:%@", , );
}
 
@end

The User code is as follows:
Copy the codeThe code is as follows:

#import <Foundation/>
 
@interface User : NSObject
 
@property (nonatomic, copy) NSString *userName;
 
@end

Copy the codeThe code is as follows:

#import ""
 
@implementation User
 
@end

At this point, the code of the Xiangyuan mode has been completed. Let’s take a look at how to use the Xiangyuan mode on the client. The code is as follows:
Copy the codeThe code is as follows:

#import ""
#import ""
#import ""
#import ""
#import ""
typedef id<WebSiteProtocol> WebsiteType;
@interface ViewController ()
 
@end

Copy the codeThe code is as follows:

@implementation ViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
// Return various specific enjoyment objects through factory methods to maintain the enjoyment objects in the pool
    WebSiteFactory *factory = [[WebSiteFactory alloc] init];
    
// Return to the specific enjoyment object
WebsiteType type1 = [factory getWebSiteCategory:@"Home"];
    User *user1 = [[User alloc] init];
= @"Zhang San";
// All the Xiangyuan objects have use methods
    [type1 use:user1];
    
WebsiteType type2 = [factory getWebSiteCategory:@"Shop"];
    User *user2 = [[User alloc] init];
= @"Li Si";
    [type2 use:user2];
    
WebsiteType type3 = [factory getWebSiteCategory:@"Case"];
    User *user3 = [[User alloc] init];
= @"Wang Wu";
    [type3 use:user3];
    
    NSInteger count = [factory getWebSiteCount];
NSLog(@"Number: %ld", (long)count);
    
}
 
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
 
@end

The output is as follows:
2015-09-12 15:59:55.322 FlyweightPattern[42020:1723017] Website classification:front page Username:Zhang San
2015-09-12 15:59:55.322 FlyweightPattern[42020:1723017] Website classification:shop Username:Li Si
2015-09-12 15:59:55.322 FlyweightPattern[42020:1723017] Website classification:Case Username:Wang Wu
2015-09-12 15:59:55.323 FlyweightPattern[42020:1723017] Number of: 3

Sharing the same resources to perform tasks may be more efficient than using personal resources to accomplish the same thing. The Encyclopedia mode can save a lot of memory by sharing some of the necessary objects.
   
When to use Encyclopedia Mode
(1) The application uses many objects;
(2) Saving objects in memory will affect memory performance;
(3) Most unique states of the object (external state) can be placed outside and lightweight;
(3) After removing the external state, fewer shared objects can be replaced by the original group of objects;
(4) The application does not rely on object labels, because shared objects cannot provide unique labels.