2013年2月25日月曜日

開発環境

『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487312-194-7)の 第11章(継承とポリモーフィズム)11.9(練習問題)練習11-3.を解いてみる。

その他参考書籍

練習11-3.

コード

using System;

abstract class Telephone
{
    protected string phonetype;
    public Telephone()
    {
        this.phonetype = "Telephone";
    }
    public abstract void Ring();
}
class ElectronicPhone : Telephone
{
    public ElectronicPhone()
    {
        this.phonetype = "Digital";
    }
    public override void Ring()
    {
        Console.WriteLine("Ringing the {0}. Pipi, Pipi.", phonetype);
    }
}
class TalkingPhone : Telephone
{
    public TalkingPhone()
    {
        this.phonetype = "Talking";
    }
    public override void Ring()
    {
        Console.WriteLine("Ringing the {0}. Talking!", phonetype);
    }
}
class Tester
{
    public void Run()
    {
        ElectronicPhone ep = new ElectronicPhone();
        TalkingPhone tp = new TalkingPhone();
        Telephone[] ts = { ep, tp };
        foreach (Telephone item in ts)
        {
            item.Ring();
        }
    }
    static void Main()
    {
        Tester t = new Tester();
        t.Run();
    }
}

入出力結果(Console Window)

Ringing the Digital. Pipi, Pipi.
Ringing the Talking. Talking!
続行するには何かキーを押してください . . .

ちなみにJavaScriptの場合。

コード(BBEdit)

$('#pre0').text('');
var Telephone = function (  ) {
    this.phonetype = "Telephone";
},
    ElectronicPhone, TalkingPhone, ep, tp, ts, i, max;
Telephone.prototype.ring = function(  ) {
    throw {
        type: "ring",
        message: "定義し忘れてる"
    };
},
ElectronicPhone = function(  ) {
    this.phonetype = "Digital",
    this.ring = function( ) {
        $('#pre0').append("Ringing the " + this.phonetype + ". Pipi, Pipi.\n");
    };
},
ElectronicPhone.prototype = new Telephone(),
TalkingPhone = function (  ) {
    this.phonetype = "Talking",
    this.ring = function () {
        $('#pre0').append("Ringing the " + this.phonetype + ". Talking!\n");
    };
},
ep = new ElectronicPhone(),
tp = new TalkingPhone(),
ts = [ep, tp];
for (i = 0, max = ts.length; i < max; i += 1) {
    ts[i].ring();
}



pythonの場合。

コード(BBEdit)

sample.py

#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-

class Telephone:
    def __init__(self):
        self._phonetype = "Telephone"
    def ring(self):
        raise Exception("ringを定義し忘れている")
class ElectronicPhone(Telephone):
    def __init__(self):
        self._phonetype = "Digital"
    def ring(self):
        print("Ringing the {0}. Pipi, Pipi.".format(self._phonetype))
class TalkingPhone(Telephone):
    def __init__(self):
        self._phonetype = "Talking"
    def ring(self):
        print("Ringing the {0}. Talking!".format(self._phonetype))
ep = ElectronicPhone()
tp = TalkingPhone()
for x in [ep, tp]:
    x.ring()

入出力結果(Terminal)

$ ./sample.py
Ringing the Digital. Pipi, Pipi.
Ringing the Talking. Talking!
$

0 コメント:

コメントを投稿