#!/usr/bin/perl use warnings; use strict; package Factory; sub new { my $classname = shift; my $self = {name => "acme", cars => [], money => 0}; return bless($self, $classname); } sub createCar { my $self = shift; my $color = shift; my $price = shift; push(@{$self->{cars}}, Car->new($self, $color, $price, 0)); } sub returnPrice { my $self = shift; my $color = shift; foreach my $car (@{$self->{cars}}) { if ($car->{color} eq $color) { return $car->{price}; } } } sub handOutCar { my $self = shift; my $purchaser = shift; my $color = shift; my $index = 0; foreach my $car (@{$self->{cars}}) { if ($car->{color} eq $color) { $car->{owner} = $purchaser; $purchaser->receiveCar($car); splice(@{$self->{cars}}, $index, 1); last; } $index++; } } sub receiveMoney { my $self = shift; my $money = shift; $self->{money} += $money; } sub showInfo { my $self = shift; my @cars = @{$self->{cars}}; my $name = $self->{name}; print "-----------------------\n"; print "Report for '$name':\n"; if ($#cars >= 0) { foreach my $car (@cars) { $car->showInfo(); print "\n"; } } else { print "$name has no cars.\n"; } print $name . "'s Money: " . $self->{money} . "\n"; print "\n"; } package Car; sub new { my $classname = shift; my $self = {owner => shift, color => shift, price => shift, km => shift}; return bless($self, $classname); } sub drive { my $self = shift; my $km = shift; $self->{km} += $km; } sub showInfo { my $self = shift; print "Car:\n"; print "Owner: " . $self->{owner}->{name} . "\n"; print "Color: " . $self->{color} . "\n"; print "Price: " . $self->{price} . "\n"; print "Km: " . $self->{km} . "\n"; } package Consumer; sub new { my $classname = shift; my $self = {name => "consumer", cars => [], money => 10000}; return bless($self, $classname); } sub buyCar { my $self = shift; my $factory = shift; my $color = shift; my $price = $factory->returnPrice($color); $factory->handOutCar($self, $color); $self->pay($factory, $price); } sub receiveCar { my $self = shift; my $car = shift; push(@{$self->{cars}}, $car); } sub pay { my $self = shift; my $vendor = shift; my $money = shift; $vendor->receiveMoney($money); $self->{money} -= $money; } sub driveCar { my $self = shift; my $carnr = shift; my $km = shift; ${$self->{cars}}[$carnr]->drive($km); } sub showInfo { my $self = shift; my @cars = @{$self->{cars}}; my $name = $self->{name}; print "-----------------------\n"; print "Report for '$name':\n"; if ($#cars >= 0) { foreach my $car (@cars) { $car->showInfo(); print "\n"; } } else { print "$name has no cars.\n"; } print $name . "'s Money: " . $self->{money} . "\n"; print "\n"; } package main; my $factory = Factory->new(); my $consumer = Consumer->new(); $factory->createCar("green", 10000); $factory->createCar("red", 7000); print "Before transaction:\n"; $factory->showInfo(); $consumer->showInfo(); $consumer->buyCar($factory, "red"); $consumer->driveCar(0, 1000); print "After transaction:\n"; $factory->showInfo(); $consumer->showInfo();