Vs 2008
A behavior of a class may have multiple implementation policies. You can extract this behavior and define it as an interface. Then, you can provide multiple implementations of this interface. These classes (Policies) can be replaced with each other without affecting the client.Code.
1. Mode UML diagram
2. Application
Examples of discounts for books are divided into general discount prices and gold discount prices. For book sellers, the two discounts are two strategies for selling books at a discount.
Idiscountstrategy. CS
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Designpattern. Strategy. BLL {< br> Public interface idiscountstrategy {< br> double calculateprice ( double price );
}
}
Commondiscountstrategy. CS
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Designpattern. Strategy. BLL {
Public Class Commondiscountstrategy: idiscountstrategy {
Idiscountstrategy members # Region Idiscountstrategy members
Public Double Calculateprice ( Double Price) {
ReturnPrice* 0.9;
}
# Endregion
}
}
Goldendiscountstrategy. CS
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Designpattern. Strategy. BLL {
Public Class Goldendiscountstrategy: idiscountstrategy {
Idiscountstrategy members # Region Idiscountstrategy members
Public Double Calculateprice ( Double Price) {
ReturnPrice* 0.7;
}
# Endregion
}
}
Book. CS
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Designpattern. Strategy. BLL {
Public Class Book {
Private Double Price;
Public Book ( Double Price) {
This. Price=Price;
}
Public Double Getpriceafterdiscount (idiscountstrategy strategy) {
ReturnStrategy. calculateprice (This. Price );
}
}
}
Client
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Using Designpattern. Strategy. BLL;
Namespace Designpattern. Strategy {
Class Program {
Static Void Main ( String [] ARGs) {
Book book1 = New Book ( 100 );
Double Commonprice = Book1.getpriceafterdiscount ( New Commondiscountstrategy ());
Console. writeline ( " Common price is {0} " , Commonprice. tostring ());
Double Goldenprice = Book1.getpriceafterdiscount ( New Goldendiscountstrategy ());
Console. writeline ( " Golden price is {0} " , Goldenprice. tostring ());
}
}
}
Output