An application of nested types- factory mode (factory mode). The so-called factory model refers to a "factory" that can produce a certain "product", in which products can only be produced by the factory. For example, a bank account ( Account
) can only Bank
be generated by a bank ( ). In C#, the account can be implemented by Bank
the internal class ( Account
), where the internal class is yes private
, it cannot be accessed from the outside, and can only be accessed through an interface ( ICount
).
Example NestedBankAccount.cs
to realize the bank account of Factory mode through nested class:
using System;
using System.Collections;
public interface IAccount // 定义接口
{
long Number {
get; }
decimal Balance {
get; }
void Deposit(decimal amount);
void Withdraw(decimal amount);
}
public class Bank
{
public IAccount OpenAccount() {
IAccount acc = new Account();
accounts[acc.Number] = acc;
return acc;
}
private readonly Hashtable accounts = new Hashtable();
private sealed class Account : IAccount
{
public long Number => number;
public decimal Balance => balance;
public void Deposit(decimal amount) {
balance += amount;
}
public void Withdraw(decimal amount) {
balance -= amount;
}
private decimal balance = 0; // decimal 是高精度浮点类型
private static long nextNumber = 123;
private readonly long number = nextNumber++;
}
}
class Test
{
static void Main() {
Bank bank = new Bank();
IAccount account = bank.OpenAccount();
account.Deposit(100.00M);
account.Withdraw(40.00M);
Console.WriteLine("Account{0}has ${1}", account.Number, account.Balance);
}
}