面向对象设计模式之单例模式

用PHP来构造一个单例类

<?php

	class Single {
		private static $self;

		final protected function __construct() {

		}

		final public static function get_self() {
			if (Single::$self instanceof Single)
				return Single::$self;

			Single::$self = new Single();

			return Single::$self;
		}

		function __clone() {
			trigger_error('对不起, 不允许克隆', E_USER_WARNING);
		}
	}

	$s = Single::get_self();
	$s1 = Single::get_self();

	var_dump($s == $s1);

 最终结果

可以看到,两个对象实例是相等的。说明,这两个对象全部指向了同一个类。从而达到,单例的效果。

posted @ 2013-07-29 17:26  、包小包  阅读(85)  评论(0编辑  收藏  举报