JVM性能调优5_编写高效优雅Java程序__享学课堂

6 篇文章 0 订阅

在这里插入图片描述

面向对象:

ü 构造器参数太多怎么办(5个以上)?

使用构造者模式(build),

package com.xiangxue.ch04.builder01;

public class FoodBuilder {

    //required
    private final String foodName;
    private final int reilang;

    //optional
    private  int danbz;
    private  int dianfen;
    private  int zf;
    private  int tang;
    private   int wss;
    
    public static class Builder{
        //required
        private final String foodName;
        private final int reilang;

        //optional
        private  int danbz;
        private  int dianfen;
        private  int zf;
        private  int tang;
        private   int wss;
        
		public Builder(String foodName, int reilang) {
			super();
			this.foodName = foodName;
			this.reilang = reilang;
		}
		
		public Builder danbz(int val) {
			this.danbz = val;
			return this;
		}
        
		//.......
		
		public FoodBuilder build() {
			return new FoodBuilder(this);
		}
    }
    
    private FoodBuilder(Builder builder) {
    	foodName = builder.foodName;
    	reilang = builder.reilang;
    	danbz = builder.danbz;
    	//.....
    	
    }
    
    public static void main(String[] args) {
    	FoodBuilder foodBuilder 
    	= new FoodBuilder.Builder("food2", 1000).danbz(100)
    	//.....
    	.build();

	}
}
抽象构造:
package com.xiangxue.ch04.builder01.buildpattern;

/**
 *类说明:客户端
 */
public class Mingyun {

    public static void main(String[] args) {
    	System.out.println("create NvWa");
    	NvWa nvwa =  new NvWa();
    	nvwa.buildPerson(new ManBuilder());
    	nvwa.buildPerson(new WomanBuilder());
    	
    }
}
package com.xiangxue.ch04.builder01.buildpattern;

import com.xiangxue.ch04.builder01.buildpattern.product.Person;

/**
 *类说明:导演者
 */
public class NvWa {
	
	public Person buildPerson(PersonBuilder pb) {
		pb.buildHead();
		pb.buildBody();
		pb.buildFoot();
		return pb.createPerson();
	}

}
package com.xiangxue.ch04.builder01.buildpattern;

import com.xiangxue.ch04.builder01.buildpattern.product.Man;
import com.xiangxue.ch04.builder01.buildpattern.product.Person;

/**
 *类说明:具体建造者
 */
public class ManBuilder extends PersonBuilder {
	
	private Person person;
	
	public ManBuilder() {
		this.person = new Man();
	}

	@Override
	public void buildHead() {
		person.setHead("Brave Head");
		
	}

	@Override
	public void buildBody() {
		person.setBody("Strong body");
		
	}

	@Override
	public void buildFoot() {
		person.setFoot("powful foot");
		
	}

	@Override
	public Person createPerson() {
		return person;
	}
}
package com.xiangxue.ch04.builder01.buildpattern;

import com.xiangxue.ch04.builder01.buildpattern.product.Person;

/**
 *类说明:抽象建造者
 */
public abstract class PersonBuilder {
	
	//建造部件
	public abstract void buildHead();
	public abstract void buildBody();
	public abstract void buildFoot();
	
	public abstract Person createPerson();

}
package com.xiangxue.ch04.builder01.buildpattern;

import com.xiangxue.ch04.builder01.buildpattern.product.Person;
import com.xiangxue.ch04.builder01.buildpattern.product.Woman;

/**
 *类说明:具体建造者
 */
public class WomanBuilder extends PersonBuilder {
	
	private Person person;
	
	public WomanBuilder() {
		this.person = new Woman();
	}

	@Override
	public void buildHead() {
		person.setHead("Pretty Head");
		
	}

	@Override
	public void buildBody() {
		person.setBody("soft body");
		
	}

	@Override
	public void buildFoot() {
		person.setFoot("long white foot");
		
	}

	@Override
	public Person createPerson() {
		return person;
	}
	
	

}
package com.xiangxue.ch04.builder01.buildpattern.product;


/**
 *类说明:具体的产品
 */
public class Man extends Person {
    public Man() {
        System.out.println("create a man");
    }

    @Override
    public String toString() {
        return "Man{}";
    }
}
package com.xiangxue.ch04.builder01.buildpattern.product;


/**
 *类说明:产品类,抽象的
 */
public abstract class Person {

    protected String head;
    protected String body;
    protected String foot;

    public String getHead() {
        return head;
    }

    public void setHead(String head) {
        this.head = head;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getFoot() {
        return foot;
    }

    public void setFoot(String foot) {
        this.foot = foot;
    }
}
package com.xiangxue.ch04.builder01.buildpattern.product;


/**
 *类说明:具体的产品
 */
public class Woman extends Person {

    public Woman() {
        System.out.println("create a Woman");
    }

    @Override
    public String toString() {
        return "Woman{}";
    }
}
不需要实例化的类应该构造器私有

如:工具类

不要创建不必要的对象
package com.xiangxue.ch04.createobj03;

public class Sum {
	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		
		Long sum = 0L;//对象
		for(long i=0;i<Integer.MAX_VALUE;i++) {
			sum = sum+i;
			//new 20多亿的Long的实例
		}

		System.out.println("spend time:"+(System.currentTimeMillis()-start)+"ms");
	}
}

Long sum = 0L;改为long sum时,花费时间就很少,因为每次sum = sum+i;时就new出了一个新对象。

避免使用终结方法

在这里插入图片描述
Finalize方法就算代码里写了,也不一定会被jdk调用;
ü 使类和成员的可访问性最小化
ü 使可变性最小化
ü 优先使用复合

继承:

package com.xiangxue.ch04.countset07;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;

/**
 *类说明:统计增加的元素个数,继承
 */
public class ExtendsHashSet<E> extends HashSet<E> {
	private int addCount = 0;//计数器

	public ExtendsHashSet() {
	}

	@Override
	public boolean add(E e) {
		addCount++;
		return super.add(e);
	}
	
	@Override
	public boolean addAll(Collection<? extends E> c) {
		addCount = addCount+c.size();
		return super.addAll(c);
	}

	public int getAddCount() {
		return addCount;
	}

	public static void main(String[] args) {
		ExtendsHashSet<String> s = new ExtendsHashSet<String>();
		s.addAll(Arrays.asList("Mark","James","Lison"));
		System.out.println(s.getAddCount());  // 结果为6,addAll调用了add方法
	}
}

组合:

package com.xiangxue.ch04.countset07;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 *类说明:统计增加的元素个数,组合
 */
public class CompositionSet<E>{
	private int addCount = 0;
	private final Set<E> s;

	public int getAddCount() {
		return addCount;
	}

	public CompositionSet(Set<E> s) {
		super();
		this.s = s;
	}
	
	public boolean add(E e) {
		addCount++;
		return s.add(e);
	}
	
	public boolean addAll(Collection<? extends E> c) {
		addCount = addCount+c.size();
		return s.addAll(c);
	}

	public static void main(String[] args) {
		CompositionSet<String> s = new CompositionSet<>(new HashSet<String>());
		s.addAll(Arrays.asList("Mark","James","Lison"));
		System.out.println(s.getAddCount()); // 结果为3
	}
}

在这里插入图片描述
方法

可变参数要谨慎使用
可变参数允许传0个参数;
package com.xiangxue.ch04.varargs09;

import java.util.Collections;

import com.xiangxue.ch04.enmu12.SampleIntConst;

public class VarArags {
	
	//private User user ;
	
	public static void userOper(int count) {
		//SampleIntConst.ORDER_DEPOT_PAID;
		if (count<0) {
			throw new IllegalArgumentException("");
		}
	}
	
	//可能很多 0~很多
	static int sum(int... args) {
		int sum = 0;
		for (int arg : args)
			sum += arg;
		return sum;
	}
	
	//要求参数的个数,是1~多个
	//
//	static int sum1(int... args) {
//		if(args.length==0) {
//			//做点异常处理
//		}
//		if(args[0]==100) {
//			
//		}
//		for(int i=1;i<args.length;i++) {
//			int sum = 0;
//			sum += args[i];
//			return sum;	
//		}
//	}
//	
//	static int sum2(int flag, int... args) {
//		if(flag==100) {
//			
//		}
//		int sum = 0;
//		for (int arg : args)
//			sum += arg;
//		return sum;
//		return Collections.EMPTY_LIST;
//	}
	
	
}
返回零长度的数组或集合,不要返回null
集合可以返回这个:
return Collections.EMPTY_LIST;
优先使用标准的异常
public static void userOper(int count) {
		//SampleIntConst.ORDER_DEPOT_PAID;
		if (count<0) {
			throw new IllegalArgumentException("");
		}
}

在这里插入图片描述
此处,子类应该重写该方法,然后子类调用自己重写后的方法,如果子类没有重写,就会调用到父类的该方法,此时,父类抛出异常。

通用程序设计
用枚举代替int 常量
package com.xiangxue.ch04.enmu12;

public class SampleIntConst {
	
	//延时订单状态
	public static final int ORDER_DEPOT_UNPAY = 0;
	//public static final String ORDER_DEPOT_UNPAY_DESC = "unpay";
	public static final int ORDER_DEPOT_PAID = 3;
	public static final int ORDER_DEPOT_TIMOUT = 2;
	
	//物流订单状态
	public static final int ORDER_LOGISTICS_READY = 0;
	public static final int ORDER_LOGISTICS_TRANSPORT = 1;
	public static final int ORDER_LOGISTICS_ARRIVED = 2;
	
	//
	public enum Depot{UNPAY,PAID,TIMOUT}//0,1,2
	public enum Logistics{READY,TRANSPORT,ARRIVED}
	
	public static void main(String[] args) {
		
		System.out.println(Depot.UNPAY);
		System.out.println(Depot.UNPAY.ordinal());
//		if(==0)
//			switch status
//			case 0:
	
	}
}

写代码时可能会写错,调用该常亮时,订单的状态常量可能使用到库存的状态常量,只是常量名有变化,如果没有仔细看,就over了。

package com.xiangxue.ch04.enmu12;

public enum DepotEnum {
	UNPAY(0,"未支付"),PAID(1,"已支付"),TIMOUT(-1,"超时");
	
	private int status;
	private String desc;
	private String dbInfo;//其他属性
	
	private DepotEnum(int status, String desc) {
		this.status = status;
		this.desc = desc;
	}

	public int getStatus() {
		return status;
	}

	public String getDesc() {
		return desc;
	}

	public String getDbInfo() {
		return dbInfo;
	}
	
	public int calcStatus(int params) {
		return status+params;
	}
	
	public static void main(String[] args) {
		for(DepotEnum e:DepotEnum.values()) {
			System.out.println(e+":"+e.calcStatus(14));
		}
	}
}
枚举和行为绑定:
package com.xiangxue.ch04.enmu12;

/**
 *类说明:枚举和行为绑定
 */
public class ActiveEnum {
	
	public enum NormalActive{
		PLUS,MINUS,MULTI,DIVIDS,DIFFER;
		
		double oper(double x,double y) {
			switch(this) {
			case PLUS:return x+y;
			case MINUS:return x-y;
			case MULTI:return x*y;
			case DIVIDS:return x/y;
			}
			throw new UnsupportedOperationException();
		}		
	}
	
	public enum BetterActive{
		PLUS {
			@Override
			double oper(double x, double y) {
				return x+y;
			}
		},MINUS {
			@Override
			double oper(double x, double y) {
				return x-y;
			}
		};
		
		abstract double oper(double x,double y);
		
//		double oper(double x,double y) {
//			switch(this) {
//			case PLUS:return x+y;
//			case MINUS:return x-y;
//			case MULTI:return x*y;
//			case DIVIDS:return x/y;
//			
//			//default:
//			}
//			throw new UnsupportedOperationException();
//		}		
	}
	public static void main(String[] args) {
		System.out.println(NormalActive.PLUS.oper(0.1, 0.2));
	}

}
//计算加班费:
package com.xiangxue.ch04.enmu12;

/**
 *类说明:加班费计算,工作日加班2倍,节假日3倍
 */
enum PayDay {
	MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY,WUYI;
	
	private static final int HOURS_WORK = 2;
	private static final int HOURS_REST = 3;
	
	//超时时间
	double pay(double hoursOvertime) {
		switch(this) {
		case SATURDAY:case SUNDAY:
			return hoursOvertime*HOURS_REST;
		default:
			return hoursOvertime*HOURS_WORK;
		}
	}	
}
//策略枚举:
package com.xiangxue.ch04.enmu12;
/**
 *类说明:加班费计算,工作日加班2倍,节假日3倍
 */
public enum BetterPayDay {
	MONDAY(PayType.WORK), TUESDAY(PayType.WORK), WEDNESDAY(
			PayType.WORK), THURSDAY(PayType.WORK), FRIDAY(PayType.WORK), 
	SATURDAY(PayType.REST), SUNDAY(PayType.REST),WUYI(PayType.REST);

	private final PayType payType;//成员变量

	BetterPayDay(PayType payType) {
		this.payType = payType;
	}

	double pay(double hoursOvertime) {
		return payType.pay(hoursOvertime);
	}

	//策略枚举
	private enum PayType {
		WORK {
			double pay(double hoursOvertime) {
				return hoursOvertime*HOURS_WORK;
			}
		},
		REST {
			double pay(double hoursOvertime) {
				return hoursOvertime*HOURS_REST;
			}
		};
		
		private static final int HOURS_WORK = 2;
		private static final int HOURS_REST = 3;

		abstract double pay(double hoursOvertime);//抽象计算加班费的方法
	}
	
	public static void main(String[] args) {
		System.out.println(BetterPayDay.MONDAY.pay(7.5));
	}
}
将局部变量的作用域最小化
精确计算,避免使用float 和double
当心字符串连接的性能
package com.xiangxue.ch04.StringUnion15;

public class Test {
    private static class Log{

    	
        public static void debug(String msg){
            if (isDebug()) System.out.println(msg);
        }

        public static boolean isDebug(){
            return false;
        }
    }

    public static void main(String[] args) {
        int count = 100000000;
        long start = System.currentTimeMillis();
//        StringBuiler
//        StringBuffer;
//        "a"+"b"+"";
        for(int i = 0;i<count;i++){

            Log.debug("The system is running and the time is "
                    +System.currentTimeMillis()
                    +" now,Let's do another thing:"+System.nanoTime());

        }
        System.out.println("直接打印模式,次数:"+count+":spend time :"
                +(System.currentTimeMillis()-start)+"ms");

        start = System.currentTimeMillis();
        for(int i = 0;i<count;i++){
            if(Log.isDebug())
                Log.debug("The system is running and the time is "
                        +System.currentTimeMillis()
                    +" now,Let's do another thing:"+System.nanoTime());
        }
        System.out.println("先判断再打印模式,次数:"+count+":spend time :"
                +(System.currentTimeMillis()-start)+"ms");


    }
}

在这里插入图片描述
控制方法的大小

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值