设计模式---享元模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
class MovieTheater
{
private Hashtable movies = new Hashtable();

public void GiveMeAMovie(string name)
{
Movie m;
if (movies.ContainsKey(name))
{
m = (Movie) movies[name];
}
else
{
m = new ConcreteMovie(name);
movies.Add(name, m);
}

m.ShowTheMovie();
}

public void HowManyMoviesHaveWeOrdered()
{
Console.WriteLine(movies.Count);
}
}

abstract class Movie
{
protected string name;

public Movie(string n)
{
this.name = n;
}

public abstract void ShowTheMovie();
}

class ConcreteMovie : Movie
{
public ConcreteMovie(string n)
: base(n)
{
}

public override void ShowTheMovie()
{
Console.WriteLine(name);
}
}

class Client
{
public static void Main()
{
MovieTheater mth = new MovieTheater();
mth.GiveMeAMovie("Hell Boy");
mth.GiveMeAMovie("Wanted");
mth.GiveMeAMovie("Wall-E");
mth.GiveMeAMovie("Hell Boy");
mth.GiveMeAMovie("Hell Boy");
mth.GiveMeAMovie("Wanted");
mth.GiveMeAMovie("Wall-E");
mth.GiveMeAMovie("Hell Boy");
mth.HowManyMoviesHaveWeOrdered();
Console.Read();
}
}
}