Jump to content

Singleton Factory


TheMagician

Recommended Posts

I have 2 classes; AnonymousUser (Null Object) and User (has some properties and methods). Both classes extend AbstractUser. Then I have a FactoryUser class that creates a proper object when called (AnonymousUser for guests and User for normal users). However, I was wondering how I would implement it so that AnonymousUser and User classes can't be called outside FactoryUser class (which would use Singleton pattern to create only one instance of either class). This would be to prevent so that when FactoryUser is called and an object is created from either class, you wouldn't be able to create, say, AnonymousUser AND User classes, which wouldn't make sense or multiple same objects for the user.

 

So what I want is:

 

$user = new AnonymousUser(); // FAIL
$user = new User(); // FAIL
$user = new FactoryUser::createUser( 0 ); // returns AnonymousUser object
$user = new FactoryUser::createUser( 1 ); // returns previously created object or raises an Exception
$user = new FactoryUser::createUser( 0 ); // same as above

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/177334-singleton-factory/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.