in reply to Re: single instance shared with module
in thread single instance shared with module

main and B both use a method in A (say WriteLog). I thought it'd be a waist to make two instances of A.

Also, when main instantiates A, it passes a couple of parameters to it that B doesn't (need to) know.
  • Comment on Re: Re: single instance shared with module

Replies are listed 'Best First'.
Re: Re: Re: single instance shared with module
by sauoq (Abbot) on Sep 16, 2002 at 20:58 UTC

    Well, as I said, you can pass an instance of A (which is an object) to B and B can then call your the object's WriteLog method. You probably would want to pass the instance to B's constructor and allow B to contain the instance of A so it could use it wherever it needed it.

    If A is a class implementing a log file and WriteLog() is a method to write an entry to, say, an open logfile managed by an instance of A and you need to write to the same log file from both the main and B packages, then this approach probably makes sense. Just make sure you document that B uses an instance of A to write to a log.

    Update: Here is some example code:

    #!/usr/bin/perl -w use strict; package A; sub new { my $class = shift; my ($fh) = @_; bless { FH => $fh }; } sub WriteLog { my $self = shift; my $fh = $self->{FH}; print $fh "[",scalar localtime,"] ",@_,"\n" } package B; sub new { my $class = shift; my ($logobj) = @_; bless { A => $logobj }; # B contains instance of A. } sub Foo { my $self = shift; my $log = $self->{A}; $log->WriteLog("B::Foo wrote this!"); } package main; my $A = A->new(\*STDOUT); my $B = B->new($A); # Pass instance of A to B's constructor. $A->WriteLog("main wrote this!"); # main uses instance of A. $B->Foo(); # B also uses it.
    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Re: Re: single instance shared with module
by mojotoad (Monsignor) on Sep 16, 2002 at 20:48 UTC
    Sounds like you might want to pull the WriteLog stuff out into a third class, C. Give the first two classes, A and B, a has-a relationship to the new class C. If there's not too much overhead then A and B can maintain their own instances of C. If there's lots of overhead, then A and B can share a single instance of C by passing the instance reference to the constructors for A and B. Or you can make C a singleton class such that repeated calls to it's constructor yield the same object.

    Matt

      All A has is WriteLog. Why would i want to pull it out just to put it in C?

      And design patters sound great but really all i need is a way to pass the instance in main to B.

      I will try passing it when i cann B's new method.