设计模式之策略模式,设计模式策略
分享于 点击 29460 次 点评:33
设计模式之策略模式,设计模式策略
Ps:在大学期间,使用Java写了不少的程序,主要是Java Web方面,然而在Java的Web应用开发中多使用现有的框架,所以Java其他方面的知识接触的比较少,有一次无意在某论坛中获知Java初级程序员必备的三本图书,分别是Head First Design Pattern,Effective Java,Java并发实战,分别讲述了面向对象语言的设计模式,如何写出高效的Java代码,Java并发编程。作为一个想把Java学好的程序员,想利用这个暑假的时间,将这三本书学完,在学习的过程中,想把一些问题,思考,总结和自己的一些想法写下来,还希望读者能过批评指正,共同进步。
在学习设计模式之前,首先要弄明白什么是面向对象编程?什么是抽象?什么是设计模式?
面向对象编程是将对象作为程序的基本单位,将所有的事物都抽象为对象,通过继承,多态,抽象等方法来增强程序的重用性,灵活性和可扩展性。
抽象是指将事物使用数据表示,在面向对象编程中,抽象一般是使用对象的属性和行为来表示。
设计模式是前人在程序设计中,经时间考验过的设计经验。
现在正式进入设计模式的学习,首先是设计模式中的策略模式。
策略模式的正式定义:定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
我的一些理解:
现有一个要使用脸部识别算法的应用,目前脸部识别的算法族包括算法A(algorithm A),算法B(algorithm B),算法C(algorithm C)等。
使用策略模式来实现这个应用如下,
public class FaceRecognitionApplication
{
private Algorithm algorithm = null;
public FaceRecognitionApplication(){}
public void setAlgorithm(Algorithm algorithm)
{
this.algorithm = algorithm;
}
public void recognition()
{
if(algorithm != null)
algorithm.run();
}
}
public interface Algorithm
{
public void run();
}
public class AlgorithmA implements Algorithm
{
public void run()
{
System.out.println("A is running");
}
}
public class AlgorithmB implements Algorithm
{
public void run()
{
System.out.println("B is running");
}
}
public class AlgorithmC implements Algorithm
{
public void run()
{
System.out.println("C is running");
}
}
测试代码如下:
public class Test
{
public static void main(String[] args)
{
FaceRecognitionApplication application = new FaceRecognitionApplication();
application.setAlgorithm(new AlgorithmA());
application.recognition();
application.setAlgorithm(new AlgorithmB());
application.recognition();
application.setAlgorithm(new AlgorithmC());
application.recognition();
}
}
策略模式所遵循的设计原则:
1、针对接口编程,而不是针对实现编程(这里的接口编程是指针对超类型编程,一般可以使用接口和抽象类来实现);
2、对于变化的部分,从不变中抽离出来封装。
相关文章
- 暂无相关文章
用户点评