Does it makes sense to use state pattern with virtual proxies?

Sta*_*123 5 java oop design-patterns lazy-initialization state-pattern

class HeavyweightObjcet
{
    public void operate() {
        System.out.println("Operating...");
    }
}

class LazyInitializer
{
    HeavyweightObjcet objcet;

    public void operate()
    {
        if (objcet == null)
            objcet = new HeavyweightObjcet();
        objcet.operate();
    }
}
Run Code Online (Sandbox Code Playgroud)

Here I'm making a virtual proxy for a heavyweight object. Each time before calling HeavyweightObject::operate, the program checks first whether the object is null or not. This part is checked once and only once through the entire lifetime of the object.

A possible improvement maybe using the state pattern like this:

class HeavyweightObjcet
{
    public void operate() {
        System.out.println("Operating...");
    }
}

class LazyInitializer
{
    HeavyweightObjcet objcet;
    State state = new UninitializedState(this);

    public void operate()
    {
        state.operate();
    }
}

abstract class State
{
    LazyInitializer initializer;

    public State(LazyInitializer initializer)
    {
        this.initializer = initializer;
    }

    abstract void operate();
}

class UninitializedState extends State
{
    public UninitializedState(LazyInitializer initializer) {
        super(initializer);
    }

    @Override
    public void operate() {
        initializer.objcet = new HeavyweightObjcet();
        initializer.state = new InitializedState(initializer);
        initializer.operate();
    }
}

class InitializedState extends State
{
    public InitializedState(LazyInitializer initializer) {
        super(initializer);
    }

    @Override
    public void operate() {
        initializer.objcet.operate();
    }
}
Run Code Online (Sandbox Code Playgroud)

Does this solution make sense?

Is there any possible improvement to the code?

Are there any examples to something like this that's done before?

Is it an unnecessary complication or does it worth it or does it depend on the situation?

Does it make the code faster? I mean, the extra function calls may be slower than just a simple conditional.

CKi*_*ing 2

这是不必要的并发症还是值得,或者取决于具体情况?

虽然在使用状态模式时只有 2 个状态是完全可以的,但在这种特殊情况下,由于以下原因,这绝对是一种过度杀伤力:

  1. UninitializedState从->只会发生一次状态转换 InitailizedState。一旦HeavyWeightObjcet 初始化,您绝对不会在从InitializedState->转换UninitializedState或反之亦然之间交替
  2. 我们有YAGNI(你不会需要它)和KISS(保持简单,愚蠢)等设计原则是有原因的。不要在代码的第一次迭代中引入复杂性。让设计作为持续重构的一部分不断发展。
  3. 虽然上面的例子在纸面上看起来不错,但现实世界却完全不同。现实世界中的代码还有更重要的问题需要解决。(例如,该operate方法是线程安全的吗?)

它会使代码更快吗?我的意思是,额外的函数调用可能比简单的条件调用慢。

当涉及到性能时,这个领域太小了,无需担心阅读:微优化

最后但并非最不重要的一点是,状态模式使我们能够遵守开闭原则。operate正如这个例子所示,就初始化而言,没有令人信服的理由来改变该方法HeavyWeightObject。此外,初始化代码首先应该位于构造函数中,而不是operate方法中。