java之策略模式
Posted xblovexb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java之策略模式相关的知识,希望对你有一定的参考价值。
1 //抽象被裝飾者 2 public abstract class Component{ 3 private String lsh="output:";//output:生成流水號 4 public abstract String operation();//抽象方法(包裝) 5 public String getlsh(){ 6 return lsh; 7 } 8 } 9 //具體被裝飾者 10 public class detailComponent{ 11 @Override 12 public String operation(){ 13 return getlsh(); 14 } 15 } 16 //具體裝飾者:常量 17 public class constant extends Component{ 18 private Component com; 19 private String cl; 20 public constant( Component com,String cl){ 21 this.com=com; 22 this.cl=cl; 23 } 24 @Override 25 public String operation(){ 26 return com.operation()+cl; 27 } 28 } 29 //具體裝飾者:日期 30 public class time extends Component{ 31 private Component com; 32 private String rq 33 public time ( Component com,String rq){ 34 this.rq=rq; 35 this.com=com; 36 } 37 @Override 38 public void operation(){ 39 return com.operation()+rq; 40 } 41 } 42 //具體裝飾者:自增數 43 public class num extends Component{ 44 private String num 45 public num ( Component com,String num){ 46 this.com=com; 47 this.num=num; 48 } 49 @Override 50 public void operation(){ 51 com.operation()+num; 52 } 53 } 54 //測試 55 public class test { 56 public static void main(String[] args) { 57 //客戶端傳來 三個 規則 58 String a = "DB"; 59 String b = "YYYY"; 60 String c = "001"; 61 //當前時間 字符串 62 b = cDate(b); 63 Component com = new detailComponent();//創建 被裝飾者 64 com = new num (new time(new constant(com,a),b),c);//裝飾 65 com.operation();//輸出為:output:DB2020001 66 Component com2 = new detailComponent();//創建 被裝飾者 67 c = autoNum(c);//c+1 68 com2 = new num (new time(new constant(com2,a),b),c); 69 } 70 public String autoNum(String c){ 71 StringBuilder strbd = new StringBuilder(); 72 int i,j; 73 i = Integer.parseInt(c); 74 i++; 75 int d = c.length()-Integer.toString(i).length(); 76 j=0; 77 while(j<d){ 78 j++; 79 strbd.append("0"); 80 } 81 strbd.append(i); 82 return strbd.toString(); 83 } 84 public String cDate(String b){ 85 SimpleDateFormat dateFormat ; 86 String str = null; 87 if(b.length()==8) { 88 str = "YYYYMMDD"; 89 } 90 else if(b.length()==6){ 91 str = "YYYYMM"; 92 } 93 else if(b.length()==4){ 94 str = "YYYY"; 95 }else { 96 return "error"; 97 } 98 dateFormat = new SimpleDateFormat(str); 99 String currentDate = dateFormat.format(new Date()); 100 return currentDate; 101 } 102 }
以上是关于java之策略模式的主要内容,如果未能解决你的问题,请参考以下文章