设计模式-策略模式

当完成一件事情可以有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("坐飞机");
		
	    }
	
    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值