返回缓存实例的工厂是否违反了 CQS(命令查询分离)?

Does a factory returning a cached instance violates the CQS (Command query separation)?

我将 command and query separation principle 理解为:函数必须 return(计算)一个值并且没有副作用 return void 并且有副作用(改变其状态上下文)。

这个定义非常好用,因为它在概念上非常简单。然而,当使用这种工厂时它似乎变得平淡无奇:

   class House {
     static House? _cachedInstance; // private in dart

     House.privateConstructor();

     factory() create() {
       if (_cachedInstance == null) {
         _cachedInstance = House.privateConstructor();
       } 
       return _cachedInstance!; 
     }
   }

此处更改了一些状态(创建了缓存实例)。

维基百科关于 CQS 的文章说“提出问题不应该改变答案”。不过这里不是这种情况。

所以我想知道我原来的理解是错误的还是部分错误的。

我想说单例确实破坏了 CQS,我不认为这是一件坏事,因为代码非常简单,CQS 的优势并没有真正体现出来,但是这是一种在不破坏 CQS 的情况下实现单例的方法,副作用是实例 getter 可以为空

class Singleton {
  static Singleton? _instance;

  static Singleton? get instance => _instance;

  Singleton._private();

  static void ensureCreated() {
    _instance ??= Singleton._private();
  } 
}

这样:

Singleton.ensureCreated();
Singleton singleton = Singleton.instance!;