View the policy mode in the design mode from "if there are several Prices of 10, 20, 50, please sort them out by code"

Source: Internet
Author: User

Today, I reviewed my strategy model and shared some of my thoughts with you... I am only a technical scum. What I understand will inevitably have great limitations or even errors. Please take a critical look at it .... Do not vomit if you are not happy


Definition: policy pattern is an object behavior pattern in design pattern. It abstracts the algorithms used into a separate class. Generally, we can use this design mode to complete the same thing in multiple classes in different ways.

For example, I believe that many people will soon write the following code when they see the question "if there are several Prices of 10, 20, 50, please sort and output them in order, before writing, I still don't forget to ask, "Do you have any requirements on time complexity ??? What is the size of the data to be processed ???", At this time, people usually smile and say, "there is no requirement for time complexity. You can assume that the data size is XX...

Soon, the code similar to the following came out.

/** Price. cpp ** Created on: May 11, 2014 * Author: pc */# include <iostream> # include <cstdio> # include <algorithm> using namespace std; int n; int price [100];/*** processing Input logic */void hanldeInput () {int I; for (I = 0; I <n; ++ I) {scanf ("% d", & price [I]) ;}/ *** compared with many of our friends here, they will find a variety of sorting algorithms .. * In fact, most of the algorithms used are: bubble sorting, selection sorting, insert sorting, Hill sorting, fast sorting, Merge Sorting, heap sorting */void sort (int price []) {for (int I = n; i> 0; -- I) {for (int j = 0; j <I-1; ++ j) {if (price [j]> price [j + 1]) {swap (price [j], price [j + 1]) ;}}}/*** processing output logic */void myprint (int price []) {// TODO output them here for (int I = 0; I <n; ++ I) {printf ("% d", price [I]);} int main () {while (scanf ("% d", & n )! = EOF) {hanldeInput (); sort (price); myprint (price );}}

Although some friends may even write the above input logic, sorting logic, and output logic into the main method, most of them will say, "depend, lao Tzu is the winner of the XX card of ACM in XX district. He used this question to give me a try .." By... This is, I see others still smile as always .... The interviewed person leaves very well ....


In fact, when I look back on such a question, I can't bear to look at the code I wrote a few years ago...

Let's talk about some of your thoughts when you encounter similar problems.

I personally think that this kind of question may focus more on not your code implementation, but your architecture when writing code.


Here are some of my thoughts:

1) according to the "Everything is an object" principle of OOP, price should be designed into a class, rather than just an int [].

2) The preceding sorting logic only applies to Int []. What if a user needs to sort a bunch of double [] data in the same logic one day ???

Do you want to press ctrl + c \ ctrl + Vand change the parameter to the double [] type ?? Currently, the sort method applies to Price-type data,

What if we need to sort data of the Human type one day ???? Is it because of the Parameter

Different Types ???

3) The above sorting logic has been written to death, that is, the Bubble Sorting is used. If the user is happy one day, I just like to sort by hill. Then, do you want to change the code again... This...


At this time, some friends may say, "I don't care. Anyway, he asked: if there are several Prices of 10, 20, 50, please sort them out by code, I only need to implement this logic. Let alone it ".. Yes. In fact, this question is only a simplified version of the user's requirements in a certain situation... For example, today the user just said, "I have a bunch of prices, you can help me sort them." Tomorrow he may say to you, "I also have a bunch of Human resources, you can also help me sort it "... The day after tomorrow, I will say to you, "I don't like your previous algorithm. Please change one ".... Then you will go crazy ....


Therefore, the following shows how to design the code using the policy pattern in this case.


1. MyComparable

public interface MyComparable {public int compareTo(Object o);}


2. MyComparator

public interface MyComparator {public int compare(Object o1,Object o2);}

3. PriceNumComparator

public class PriceNumComparator implements MyComparator {@Overridepublic int compare(Object o1, Object o2) {Price p1 = (Price)o1;Price p2 = (Price)o2;if(p1.getNum() > p2.getNum()){return 1;}else if(p1.getNum() < p2.getNum()){return -1;}return 0;}}

4. PriceWeightComparator

public class PriceWeightComparator implements MyComparator {@Overridepublic int compare(Object o1, Object o2) {Price p1 = (Price)o1;Price p2 = (Price)o2;if(p1.getWeight() > p2.getWeight()){return -1;}else if(p1.getWeight() < p2.getWeight()){return 1;}return 0;}}

5. Price

public class Price implements MyComparable{public int num;public int weight;public MyComparator comparator  = new PriceWeightComparator();public int getNum() {return num;}public void setNum(int num) {this.num = num;}public int getWeight() {return weight;}public void setWeight(int weight) {this.weight = weight;}public Price() {// TODO Auto-generated constructor stub}public Price(int num, int weight) {super();this.num = num;this.weight = weight;}@Overridepublic String toString() {return "Price [num=" + num + ", weight=" + weight + "]";}@Overridepublic int compareTo(Object o) {return comparator.compare(this, o);}}

6. Sorter

public class Sorter {public static void sort(Object[] os){int length = os.length;for(int i = length ; i > 0 ; --i){for(int j = 0 ; j < i-1 ; ++j){MyComparable c1 = (MyComparable) os[j];MyComparable c2 = (MyComparable) os[j+1];if(c1.compareTo(c2) == 1){swap(os, j, j+1);}}}}public static void swap(Object[] os ,int i,int j){Object temp = os[i];os[i] = os[j];os[j] = temp;}public static void print(Object[] os){int length = os.length;for(int i = 0 ; i < length ; ++i){System.out.print(os[i] + " ");}System.out.println();}}


7. Main // used for testing

public class Main {public static void main(String[] args) {Price[] prices = {new Price(1, 1),new Price(2, 2),new Price(3, 3)};Sorter.sort(prices);Sorter.print(prices);}}


Conclusion:

The design pattern is a kind of thing that complicate simple things. In fact, more accurately, it is a development idea that requires you to give the corresponding architecture to your desired development idea before you start to implement a specific function ....






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.