📄 class1.cs
字号:
namespace libraryItem
{
using System;
using System.Collections;
// 定义抽象LibaryItem类
abstract class LibraryItem
{
private int numCopies;
// 属性
public int NumCopies
{
get{ return numCopies; }
set{ numCopies = value; }
}
public abstract void Display();
}
//定义具体的部件类-Book。
class Book : LibraryItem
{
private string author;
private string title;
public Book(string author,string title,int numCopies)
{
this.author = author;
this.title = title;
this.NumCopies = numCopies;
}
public override void Display()
{
Console.WriteLine( "\n书 ------ " );
Console.WriteLine( " 作者: {0}", author );
Console.WriteLine( " 书名: {0}", title );
Console.WriteLine( " # 数量: {0}", NumCopies );
}
}
//定义具体的部件类-Video
class Video : LibraryItem
{
private string director;
private string title;
private int playTime;
public Video( string director, string title,
int numCopies, int playTime )
{
this.director = director;
this.title = title;
this.NumCopies = numCopies;
this.playTime = playTime;
}
public override void Display()
{
Console.WriteLine( "\n影像 ----- " );
Console.WriteLine( " 导演: {0}", director );
Console.WriteLine( " 片名: {0}", title );
Console.WriteLine( " # 数量: {0}", NumCopies );
Console.WriteLine( " 播放时间: {0}", playTime );
}
}
// 定义抽象装饰类
abstract class Decorator : LibraryItem
{
protected LibraryItem libraryItem;
public Decorator ( LibraryItem libraryItem )
{
this.libraryItem = libraryItem;
}
public override void Display()
{
libraryItem.Display();
}
}
// 定义具体装饰类
class Borrowable : Decorator
{
protected ArrayList borrowers = new ArrayList();
//调用父类的构造函数
public Borrowable( LibraryItem libraryItem )
: base( libraryItem ) {}
public void BorrowItem( string name )
{
borrowers.Add( name );
libraryItem.NumCopies--;
}
public void ReturnItem( string name )
{
borrowers.Remove( name );
libraryItem.NumCopies++;
}
public override void Display()
{
base.Display();
foreach( string borrower in borrowers )
Console.WriteLine( " 借出人: {0}", borrower );
}
}
/// <summary>
/// 装饰模式应用测试
/// </summary>
public class DecoratorApp
{
public static void Main( string[] args )
{
//创建Book及Video,并显示出来
Book book = new Book( "Schnell", "My Home", 10 );
Video video = new Video( "Spielberg",
"Schindler's list", 23, 60 );
book.Display();
video.Display();
// 增加video的borrowable属性,然后借出并显示
Console.WriteLine( "\n影像增加可借属性:" );
Borrowable borrowvideo = new Borrowable( video );
borrowvideo.BorrowItem( "张三" );
borrowvideo.BorrowItem( "李四" );
borrowvideo.Display();
Console.Read();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -