php实现设计模式————单例模式

  php实现设计模式————单例模式
  
  什么是单例模式
  
  为什么要使用单例模式
  
  php中有哪些方式实现新建一个对象实例
  
  如何阻止这种实例化实现理想的单例模式
  
  代码实现
  
  什么是单例模式
  
  为什么要使用单例模式
  
  php中有哪些方式实现新建一个对象实例
  
  1. new test();//通过new实例化对象
  
  2. 通过clone复制对象
  
  3. 通过序列化反序列化得到对象实例
  
  4. 通过类的反射实例化对象
  
  1
  
  2
  
  3
  
  4
  
  如何阻止这种实例化实现理想的单例模式
  
  1. new test();//通过new实例化对象 : 通过更改构造方法为private 阻止使用方直接new 对象
  
  3. 通过clone复制对象 : 通过定义private __clone()阻止复制操作
  
  4. 通过序列化反序列化得到对象实例 :通过定义__wakeup()阻止对象的反序列化。
  
  5. 通过类的反射实例化对象:暂时还没有相应的方法去阻止使用此方法实现对象多例
  
  1
  
  2
  
  3
  
  4
  
  代码实现
  
  <?php
  
  /**
  
  * Created by PhpStorm.
  
  * User: Uasier
  
  * Date: 2018/10/17
  
  * Time: 15:10
  
  */
  
  /**
  
  * 单例模式实例
  
  */
  
  class Singleton
  
  {
  
  /**
  
  * 私有变量存实例
  
  * @var Singleton
  
  */
  
  private static $instance;
  
  /**
  
  * 私有构造函数
  
  * Singleton constructor.
  
  */
  
  private function __construct()
  
  {
  
  var_dump('构造了对象');
  
  }
  
  /**
  
  * clone 魔术方法
  
  */
  
  private function __clone()
  
  {
  
  var_dump('复制了对象');
  
  }
  
  /**
  
  * sleep 魔术方法
  
  * @return array
  
  */
  
  public function __sleep(){
  
  //todo 如何阻止
  
  var_dump('序列化了对象');
  
  return [];
  
  }
  
  /**
  
  * wakeup 魔术方法
  
  */
  
  public function __wakeup(){
  
  //todo 如何阻止
  
  var_dump('反序列化了对象');
  
  }
  
  /**
  
  * 公有获取实例方法
  
  * @return Singleton
  
  */
  
  public static function getInstance()
  
  {
  
  if (!(self::$instance instanceof self)) {
  
  self::$instance = new self();
  
  }
  
  var_dump('返回了对象');
  
  return self::$instance;
  
  }
  
  }
  
  //*******************************单例模式测试****************************
  
  //①在Singleton没有实例的情况下获取实例
  
  $a = Singleton::getInstance();
  
  var_dump($a);
  
  //在Singleton已经有实例的情况下获取实例
  
  $b = Singleton::getInstance();
  
  var_dump($b);
  
  //②通过克隆来得到实例
  
  $c = clone $a;
  
  var_dump($c);
  
  //③通过序列化再反序列化得到实例
  
  $d = serialize($a);//序列化
  
  $e = unserialize($d);//反序列化
  
  $e->name = '反序列化';
  
  var_dump($e);
  
  //④php 反射来的到实例
  
  $obj = new ReflectionObject('Singleton');
  
  $f = $obj->newInstanceWithoutConstructor();
  
  var_dump($f);
  
  相对而言,php中四种实例对象的方式,但是我们能(合理)阻止的只有3种,
  
  如代码体现的,php的反射来获得实例是我们阻止不了的一种方式(然而java却可以),
  
  但是怎么说呢,php 的反射也不是为了让你去破解单例模式的,
  
  简而言之,我们其实不用舍本求末过分追求单例模式的完美性,毕竟实现单例模式的是程序员,使用单例模式的也是程序员。程序
  
  复制代码
  
  1 using System;
  
  2 using System.Threading.Tasks;
  
  3
  
  4 using Quartz;
  
  5 using Quartz.Impl;
  
  6 using Quartz.Logging;
  
  7
  
  8 namespace QuartzSampleApp
  
  9 {
  
  10 public class Program
  
  11 {
  
  12 private static void Main(string[] args)
  
  13 {
  
  14 LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());
  
  15
  
  16 RunProgram(www.gcyl159.com).GetAwaiter().GetResult();
  
  17
  
  18 Console.WriteLine("Press any key to close the application");
  
  19 Console.ReadKey(www.gcyl152.com/ );
  
  20 }
  
  21
  
  22 private static async Task RunProgram()
  
  23 {
  
  24 try
  
  25 {
  
  26 // Grab the Scheduler instance from the Factory
  
  27 NameValueCollection props =www.michenggw.com new NameValueCollection
  
  28 {
  
  29 { "quartz.serializer.type", "binary" }
  
  30 };
  
  31 StdSchedulerFactory factory = new StdSchedulerFactory(props);
  
  32 IScheduler scheduler = await factory.GetScheduler();
  
  33
  
  34 // and start it off
  
  35 await scheduler.Start();
  
  36
  
  37 // define the job and tie it to our HelloJob class
  
  38 IJobDetail job = JobBuilder.Create<HelloJob>(www.yigouyule2.cn)
  
  39 .WithIdentity("job1", "group1")
  
  40 .Build();
  
  41
  
  42 // Trigger the job to run now, and then repeat every 10 seconds
  
  43 ITrigger trigger = TriggerBuilder.Create()
  
  44 .WithIdentity("trigger1", "group1")
  
  45 .StartNow()
  
  46 .WithSimpleSchedule(x => x
  
  47 .WithIntervalInSeconds(10)
  
  48 .RepeatForever(www.leyouzaixian2.com))
  
  49 .Build(www.365soke.com);
  
  50
  
  51 // Tell quartz to schedule the job using our trigger
  
  52 await scheduler.ScheduleJob(job, trigger);
  
  53
  
  54 // some sleep to show what's happening
  
  55 await Task.Delay(TimeSpan.FromSeconds(60));
  
  56
  
  57 // and last shut down the scheduler when you are ready to close your program
  
  58 await scheduler.Shutdown();
  
  59 }
  
  60 catch (SchedulerException se)
  
  61 {
  
  62 Console.WriteLine(se);
  
  63 }
  
  64 }
  
  65
  
  66 // simple log provider to get something to the console
  
  67 private class ConsoleLogProvider : ILogProvider
  
  68 {
  
  69 public Logger GetLogger(string name)
  
  70 {
  
  71 return (level, func, exception, parameters) =>
  
  72 {
  
  73 if (level >= LogLevel.Info && func != null)
  
  74 {
  
  75 Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] [" + level + "] " + func(), parameters);
  
  76 }
  
  77 return true;
  
  78 };
  
  79 }
  
  80
  
  81 public IDisposable OpenNestedContext(string message)
  
  82 {
  
  83 throw new NotImplementedException();
  
  84 }
  
  85
  
  86 public IDisposable OpenMappedContext(string key, string value)
  
  87 {
  
  88 throw new NotImplementedException();
  
  89 }
  
  90 }
  
  91 }
  
  92
  
  93 public class HelloJob : IJob
  
  94 {
  
  95 public async Task Execute(IJobExecutionContext context)
  
  96 {
  
  97 await Console.Out.WriteLineAsync("Greetings from HelloJob!");
  
  98 }
  
  99 }
  
  100 }
  
  复制代码

猜你喜欢

转载自www.cnblogs.com/qwangxiao/p/9982494.html