开发者

Letting an object decide its class

I'm sorry I could not come up with a more descriptive title. My problem is the following. Assume that you have two classes A and B and you know that sometimes it may happen that some code tries to instantiate an object of type A when what is actually needed is an object of type B. The point is that the code to decide which one is the right object naturally belongs to class A and not to the client code.

In javascript (ok, js doesn't have classes, but it makes the point clear) you can simply do

function A() {
    if(some_condition) {
        return new B();
    }
    //else we proceed to customize and return our object
}

I want to do something similar in PHP. The best thing I can come up with is

class A {
    private function __construct() {
        //whatever you need to do
    }

    public static function getInstance() {
        if(some_condition) {
            return n开发者_运维知识库ew B();
        }
        else {
            return new A();
        }
    }
}

The problem is that the client code will always have to know that A is special and you have to instantiate objects with a static method.

Is there a way to delegate to A the choice of the type of object to return in a seamless way?


Unfortunately no, the best i think you can do is something like:

class Decider {

    public static function decide() {
        if(some_condition) {
            return "A";
        }
        else {
            return "B";
        }
    }
}

$new_class = Decider::decide();

$new_object = $new_class();

But then again this is really no different then the way you approached it. I wouldnt consider this an invalid design patter though, however i would leave it to an external class to do the deciding rather then have class "A" or class "B" do the deciding within them. Ideally your classes should be encapsulated in such a way that they do not require other classes unless they are member variables of the class itself or passed into the class for functional purposes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜