类 "control" 问题

Issue with classes "control"

事情是这样的.. 我有一个对象负责创建另一个不同的对象,这个创建的对象可以销毁或不销毁(这取决于用户)。技巧部分是 "creator" 对象被再次调用,如果另一个对象没有被销毁,这个 class 不能再次创建这个对象,但是如果另一个对象被销毁,这个 class 需要再次创建并继续循环。

我尝试了两种解决方案: 作为 "flag" 的全局变量,它工作正常,但我因为使用​​全局变量而被烤; 第二个是使析构函数 return 成为此标志的值,但我不能从析构函数中 return 。

除了全局变量,你们还知道其他方法吗?

非常感谢关注,干杯。

您没有指定编程语言,所以我假设使用 Perl(Moo 作为 OO 工具包)。

这是您所描述内容的可能实现:

use v5.14.0;
use warnings;

package Item {
    use Moo;

    has _owner => (
        is       => 'ro',
        weak_ref => 1,
        clearer  => 1,
    );

    sub detach {
        my ($self) = @_;
        if (my $owner = $self->_owner) {
            $self->_clear_owner;
            $owner->_clear_item;
        }
    }

    sub BUILD {
        my ($self) = @_;
        say "!! constructing $self";
    }

    sub DEMOLISH {
        my ($self) = @_;
        say "!! destroying $self";
    }
}

package Owner {
    use Moo;

    has item => (
        is      => 'lazy',
        clearer => '_clear_item',
    );
    sub _build_item {
        my ($self) = @_;
        return Item->new(_owner => $self);
    }
}

my $owner = Owner->new;
say "owner = $owner";
say "(1) owner->item = ", $owner->item;
say "(2) owner->item = ", $owner->item;
say "entering block {";
{
    my $item = $owner->item;
    say "  (3) owner->item = $item";
    $item->detach;
    say "  detached item = $item";
}
say "} leaving block";
say "(4) owner->item = ", $owner->item;
say "owner is still = $owner";

当我运行这段代码时,它产生以下输出:

owner = Owner=HASH(0x23e52f8)
!! constructing Item=HASH(0x23e4950)
(1) owner->item = Item=HASH(0x23e4950)
(2) owner->item = Item=HASH(0x23e4950)
entering block {
  (3) owner->item = Item=HASH(0x23e4950)
  detached item = Item=HASH(0x23e4950)
!! destroying Item=HASH(0x23e4950)
} leaving block
!! constructing Item=HASH(0x23eb328)
(4) owner->item = Item=HASH(0x23eb328)
owner is still = Owner=HASH(0x23e52f8)
!! destroying Item=HASH(0x23eb328)

想法是 Owner class 有一个 item 属性(它存储 Item class 的一个实例)。这个属性是惰性的,所以只按需构造(第一次使用)。

正如您查看 owner->item 行 1、2 和 3 所见,没有构造新对象:$owner 记住它的 item.

但是,可以通过调用 $owner->item->detach 显式销毁 item。这是可能的,因为 Item 的每个实例都有一个(可选的)_owner 属性;即每件物品都会记住它的主人。这是一个弱引用,否则我们将有一个引用循环(所有者使项目保持活动状态,项目使所有者保持活动状态)。

当我们调用 $item->detach 时,$item 会自动从它的所有者那里移除它自己(如果它还有一个)。一旦对它的任何其他引用消失,它就会自动销毁(在示例中,当局部变量 $item 在其块的末尾不再存在时会发生这种情况)。

$owner,已重置为初始状态,然后在下次需要时自动重新创建一个新的 item