Java设计模式---Strategy策略模式

  大话设计模式

  马士兵设计模式视频

  

Java设计模式---Strategy策略模式

Java设计模式---Strategy策略模式

 

 

1.场景介绍

  购物网站上有一个产品,有三个字段,档次,价格,重量。

  有些同学喜欢轻的,有些手头紧,想要便宜的,有些喜欢档次高的。

  那么我们为了提高网站用户体验,必须给六个按钮,按照价格升序降序,按照档次升序降序,按照重量升序降序。

 (这里只是打个比方,好像一般遇到这种情况是用Lucenc)

2.不用策略模式

package com.dingyu; import java.util.Arrays; /** * 产品类,这里为了代码代码尽可能的少,set get方法没加 * Comparable接口中有一个compareTo方法,这个方法进行两个对象比较 * Arrays.sort内部方法用到了这个compareTo方法 * 这样以后只要我的类实现了Comparable接口,排序的代码可以通用(Arrays.sort())去排序,可以自定义比较规则, * * @author dingyu * */ public class Product implements Comparable<Product> { private double quality; private double price; private int weight; public Product(double quality, double price, int weight) { this.quality = quality; this.price = price; this.weight = weight; } @Override public int compareTo(Product product) { if (this.price > product.price) return 1; else if (this.price == product.price) return 0; else return -1; } @Override public String toString() { return "价格 " + price + " 重量:" + weight + " 档次:" + quality; } public static void main(String[] args) { Product[] people = { new Product(2, 500, 50), new Product(3, 1000, 60), new Product(1, 200, 70) }; Arrays.sort(people); for (int i = 0; i < people.length; i++) { System.out.println(people[i]); } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzsssg.html