பல்லுருத்தோற்றம் (கணிப்பொறி அறிவியல்)

கட்டற்ற கலைக்களஞ்சியமான விக்கிப்பீடியாவில் இருந்து.

பொருள் நோக்கு நிரலாக்கத்தில், பல்லுருவாக்கம் (Polymorphism) என்பது ஒரு வகுப்பின் செயலிகளை, மாறிகளை, அல்லது பொருட்களை அந்த வகுப்பின் subclasses தமது தேவைகளுக்கு ஏற்றமாதிரி நிறைவேற்ற முடியும் என்ற கூற்றாகும்.

எடுத்துக்காட்டுக்கள்[தொகு]

பி.எச்.பி[தொகு]

<?php

interface IAnimal
{
    function getName();
    function talk();
}

abstract class AnimalBase implements IAnimal
{
    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }
}

class Cat extends AnimalBase
{

    public function talk()
    {
        return "Meowww!";
    }
}

class Dog extends AnimalBase
{

    public function talk()
    {
        return "Arf! Arf!";
    }
}

$animals = array(
    new Cat("Missy"),
    new Cat("Mr. Mistoffelees"),
    new Dog("Lassie")
);

foreach ($animals as $animal) {
    echo $animal->getName() . ": " . $animal->talk();
}

?>

பெர்ள்[தொகு]

Polymorphism in பெர்ள் is inherently straightforward to write because of the language's use of sigils and references. This is the Animal example in standard OO Perl:

package Animal;
sub new {
    my ($class, $name) = @_;
    bless {name => $name}, $class;
}

package Cat;
@ISA = "Animal";
sub talk {"Meow"}

package Dog;
@ISA = "Animal";
sub talk {"Woof! Woof!"}

package main;
my @animals = (
    Cat->new("Missy"),
    Cat->new("Mr. Mistoffelees"),
    Dog->new("Lassie"),
);
for my $animal (@animals) {
    print $animal->{name} . ": " . $animal->talk . "\n";
}

# prints the following:
#
# Missy: Meow
# Mr. Mistoffelees: Meow
# Lassie: Woof! Woof!

This means that Perl can also apply polymorphism to the method call. The example below is written using the Moose module in order to show modern OO practises in Perl (it is not required for method polymorphism):

{
    package Animal;
    use Moose;
    has 'name' => ( isa => 'Str', is => 'ro' );
}

{
    package Cat;
    use Moose;
    extends 'Animal';
    sub talk  { 'Meow' }
    sub likes { 'Milk' }
}

{
    package Dog;
    use Moose;
    extends 'Animal';
    sub talk  { 'Woof! Woof!' }
    sub likes { 'Bone' }
}

my @animals = (
    Cat->new( name => 'Missy' ),
    Cat->new( name => 'Mr. Mistoffelees' ),
    Dog->new( name => 'Lassie' ),
);

for my $animal ( @animals ) {
    for my $trait qw/talk likes/ {
        print $animal->name . ': ' . $trait . ' => ' . $animal->$trait;
    }
}

# prints the following:
#
# Missy: talk => Meow
# Missy: likes => Milk
# Mr. Mistoffelees: talk => Meow
# Mr. Mistoffelees: likes => Milk
# Lassie: talk => Woof! Woof!
# Lassie: likes => Bone

வெளி இணைப்புகள்[தொகு]