单例应用

创建 类 :Setting、 ImageView、 VideoView、 Singleton、

Setting.h

#import 
@interface Setting : NSObject

@property (nonatomic,assign)BOOL isWIFI;
@property (nonatomic,copy)NSString *username;

+ (Setting *)shareInstance;

@end

Setting.m

#import"Setting.h"
@implementation Setting
static Setting *instance = nil;
+ (Setting *)shareInstance
{
  if(instance == nil)
  {  
    instance = [[Setting alloc]init];
  }
  return instance;
}

@end

Singleton.h

#import 
@interface Singleton : NSObject

+ (Singleton *)shareInstace;

@end

Singleton.m

#import "Singleton.h"
@implementation Singleton

static Singleton *instance = nil;
+ (Singleton *)shareInstace
{
  if (instance == nil)
  {
    //只会执行一次
    instance = [[Singleton alloc]init];
  }

  return instance;
}

@end

VideoView.h

#import 
@interface VideoView : NSObject

//@property (nonatomic,assign)BOOL isWIFI;
- (void)playVideo;

@end

VideoView.m

#import "VideoView.h"
#import "Setting.h"
@implementation VideoView

- (void)playVideo
{
  NSLog(@"当前用户为%@",[Setting shareInstance].username);
  Setting *setting = [Setting shareIstance];
  NSLog(@"setting ---> %@",setting);
  if(setting.isWIFI)
  {
    NSLog(@"wifi环境 直接播放视频");
  }
  else
  {
    NSLog(@"提示用户当前环境为流量是否继续?");
  }
}

@end

ImageView.h

#import 
@interface ImageView : NSObject

//@property (nonatomic,assign)BOOL isWIFI;
- (void)loadImage;

@end

ImageView.m

#import "ImageView.h"
#import "Setting.h"
@implementation ImageView

- (void)loadImage
{
  NSLog(@"当前用户为%@",[Setting shareIntance].username);
  if ([Setting shareInstance].isWIFI)
  {
    NSLog(@"查看高清图片");
  }
  else
  {
    NSLog(@"加载缩略图片");
  }
}

@end

main.m

#import 
#import "Singleton.h"
#import "VideoView.h"
#import "ImageView.h"
#import "Setting.h"

void function()
{
  /*
      static: 静态声明 -> count 只创建一次
      看一下Count变量是否已经创建了,如果创建了直接拿过来用,如果没则创建
  */
  static int count = 0;
  printf("function 函数 %d\n",count);
  count++;
}

//模拟另一个文件
void videoFunc()
{
  VideoView *vv = [[VideoView alloc]init];
  [vv playVideo];
}
/*____________________________________________________________________*/


int main (int argc, const char *argv[])
{
  @autoreleasepool
  {
    Setting *setting = [Setting shareInstance];
    NSLog(@"%@",setting);
    setting.isWIFI = YES;
    setting.username = @"aaaaa";


    //要求:imageview和videoview isWIFI属性 都要从setting 中获取
    videoFunc();
    ImageView *iv = [[ImageView alloc]init];
    [iv loadIma]
  }
  return 0;
}

你可能感兴趣的:(单例应用)