#!/usr/bin/perl -w use strict; package SharedThing; sub new { my $that = shift; my $class = ref($that) || $that; return bless {"counter" => 0}, ref($that) || $that; } sub hello { my $this=shift; $this->{counter}++; printf "hello, count is [%d]\n",$this->{counter}; } package MyFactory; sub new { my $that = shift; my $class = ref($that) || $that; my $this = {}; bless $this, $class; $this->{sharedthing}=SharedThing->new(); return $this; } sub A {A->new(@_);} sub B {B->new(@_);} package A; sub new { my $that = shift; my $class = ref($that) || $that; my $this = {}; bless $this, $class; $this->{factory}=shift; # call the "hello" method of the "shared thing" so that # we can see that it's indeed a single instance $this->{factory}->{sharedthing}->hello(); return $this; } package B; our @ISA=qw(A); package main; my $factory=MyFactory->new(); my $a1=$factory->A(); my $a2=$factory->A(); my $b1=$factory->B(); my $b2=$factory->B();