Using interface 3

image_pdfimage_print

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System;

// An encryption interface.
public interface ICipher {
string encode(string str);
string decode(string str);
}

/* A simple implementation of ICipher that codes
a message by shifting each character 1 position
higher. Thus, A becomes B, and so on. */
class SimpleCipher : ICipher {

// Return an encoded string given plaintext.
public string encode(string str) {
string ciphertext = “”;

for(int i=0; i < str.Length; i++) ciphertext = ciphertext + (char) (str[i] + 1); return ciphertext; } // Return an decoded string given ciphertext. public string decode(string str) { string plaintext = ""; for(int i=0; i < str.Length; i++) plaintext = plaintext + (char) (str[i] - 1); return plaintext; } } /* This implementation of ICipher uses bit manipulations and key. */ class BitCipher : ICipher { ushort key; // Specify a key when constructing BitCiphers. public BitCipher(ushort k) { key = k; } // Return an encoded string given plaintext. public string encode(string str) { string ciphertext = ""; for(int i=0; i < str.Length; i++) ciphertext = ciphertext + (char) (str[i] ^ key); return ciphertext; } // Return an decoded string given ciphertext. public string decode(string str) { string plaintext = ""; for(int i=0; i < str.Length; i++) plaintext = plaintext + (char) (str[i] ^ key); return plaintext; } } // Use ICipher. // A class for storing unlisted telephone numbers. class UnlistedPhone { string pri_name; // supports name property string pri_number; // supports number property ICipher crypt; // reference to encryption object public UnlistedPhone(string name, string number, ICipher c) { crypt = c; // store encryption object pri_name = crypt.encode(name); pri_number = crypt.encode(number); } public string Name { get { return crypt.decode(pri_name); } set { pri_name = crypt.encode(value); } } public string Number { get { return crypt.decode(pri_number); } set { pri_number = crypt.encode(value); } } } // Demonstrate UnlistedPhone public class UnlistedDemo { public static void Main() { UnlistedPhone phone1 = new UnlistedPhone("Tom", "555-3456", new BitCipher(27)); UnlistedPhone phone2 = new UnlistedPhone("Mary", "555-8891", new BitCipher(9)); Console.WriteLine("Unlisted number for " + phone1.Name + " is " + phone1.Number); Console.WriteLine("Unlisted number for " + phone2.Name + " is " + phone2.Number); } } [/csharp]