当完成一件事情可以有n种不同策略时,可以使用策略模式.
比如从a地到b地可以坐火车也可以做飞机,完成的事都是从a到b只是实现的策略不同而已.
java代码如下:
package com.liu.pattern14;
public class TestStrategy {
public static void main(String[] args) {
Context context = new Context();
context.setVehicle(new Train());
context.go();
context.setVehicle(new Plane());
context.go();
}
}
class Context{
private IVehicle vehicle;
public IVehicle getVehicle() {
return vehicle;
}
public void setVehicle(IVehicle vehicle) {
this.vehicle = vehicle;
}
public void go(){
vehicle.go();
}
}
interface IVehicle{
public void go();
}
class Train implements IVehicle{
@Override
public void go() {
System.out.println("坐火车");
}
}
class Plane implements IVehicle{
@Override
public void go() {
System.out.println("坐飞机");
}
}
c#代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace com.liu.pattern14
{
class TestStrategy
{
static void Main(string[] args)
{
Context context = new Context();
context.Vehicle = new Train();
context.Go();
context.Vehicle = new Plane();
context.Go();
System.Console.ReadKey();
}
}
class Context{
public IVehicle Vehicle{get;set;}
public void Go(){
Vehicle.Go();
}
}
interface IVehicle{
void Go();
}
class Train : IVehicle{
public void Go() {
System.Console.WriteLine("坐火车");
}
}
class Plane : IVehicle{
public void Go() {
System.Console.WriteLine("坐飞机");
}
}
}