Factory
Definition:
<? PHP Class Example { // The factory Method Public Static Function Factory ( $ Type ){ If ( Include_once 'Drivers /'. $ Type . '. Php' ){ $ Classname = 'Driver _'. $ Type ; Return New $ Classname ;} Else { Throw New Exception ('Driver not found' );}}} ?>
Usage:
<?PHP//Load a MySQL driver$ Mysql= Example: Factory ('mysql');//Load a SQLite driver$ SQLite= Example: Factory ('sqlite');?>
Singleton
Definition:
<? PHP Class Example { // Hold an instance of the class Private Static $ Instance ; // A private constructor; prevents direct creation of Object Private Function _ Construct (){ Echo 'I am constructed' ;} // The Singleton Method Public Static Function Singleton (){ If (! Isset (SELF :: $ Instance )){ $ C = _ Class __ ; Self :: $ Instance = New $ C ;} Return SELF :: $ Instance ;} // Example Method Public Function Bark (){ Echo 'Woof! ' ;} // Prevent users to clone the instance Public Function _ Clone (){ Trigger_error ('Clone is not allowed .',E_user_error );}} ?>
Usage:
php /// This wocould fail because the constructor is private $ test = New example; /// This will always retrieve a singl E instance of the class $ test = example: Singleton (); $ test -> bark (); // This will issue an e_user_error. $ test_clone = clone ( $ test ); ?>