前言:网上许多一些推送的demo,功能是实现了,但是很多并没有做到,随来随去的效果,即可以在多个项目来回切换,每次还要多次集成或者复制代码,为了解决这样问题,今天我采用工厂模式去实现这样的功能模块封装。
1、demo中我采用了工厂模式、协议代理、runtime运行时;
2、demo中我对极光和友盟采用了一个简洁的工厂管理,来实现将对象抽象出来,最后采用更高的工厂来对极光和友盟工厂进行管理,通过这个工厂来快速切换极光和友盟推送;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
FactoryManager *manager = [FactoryManager new];
manager.delegate = self;
// 需要极光推送,把此注释打开,然后把友盟推送的代码注释掉,其余均不用操作
id<PushProtocol>factory = [manager getJPushFactory:launchOptions];
// 友盟推送
// id<PushProtocol>factory = [manager getUMessageFactory:launchOptions];
return YES;
}
3、通过在最高的工厂设置代理使用runtime,可以避免导入极光工厂的头文件(JPushFactory)和友盟工厂的头文件(UMessageFactory),这样一来,删除他们其中,都不会报错
#import "FactoryManager.h"
/** 使用运行动态时,以免删除JPushFactory或者UMessageFactory报错 */
#import <objc/message.h>
@interface FactoryManager ()<YWPushMethodProtocol>
@end
@implementation FactoryManager
- (id<PushProtocol>)getJPushFactory:(NSDictionary *)launchOptions{
Class c_ss = NSClassFromString(@"JPushFactory");
id<PushProtocol> JPushF = [[c_ss alloc] initWithLaunchOptions:launchOptions];
[self updateVariable:JPushF];
return JPushF;
}
- (id<PushProtocol>)getUMessageFactory:(NSDictionary *)launchOptions{
Class c_ss = NSClassFromString(@"UMessageFactory");
id<PushProtocol> UM = [[c_ss alloc] initWithLaunchOptions:launchOptions];
[self updateVariable:UM];
return UM;
}
/** 修改变量 */
1. (id)updateVariable:(id<PushProtocol>)otherClass
{
unsigned int count = 0;
//获取属性列表
Ivar *members = class_copyIvarList([otherClass class], &count);
//遍历属性列表
for (int i = 0 ; i < count; i++) {
Ivar var = members[i];
//获取变量名称
const char *memberName = ivar_getName(var);
//获取变量类型
const char *memberType = ivar_getTypeEncoding(var);
NSLog(@"%s----%s", memberName, memberType);
Ivar ivar = class_getInstanceVariable([otherClass class], memberName);
NSString *typeStr = [NSString stringWithCString:memberType encoding:NSUTF8StringEncoding];
//判断类型
if ([typeStr isEqualToString:@"@\"<YWPushMethodProtocol>\""]) {
//修改值
object_setIvar(otherClass, ivar, self);
}
}
return otherClass;
}
demo请转github:https://github.com/flyOfYW/YWPushFactoryDemo