java学习

java学习

 

Java的方法的泛型

package com;
import java.util.List;
public class App<T> {
/**
* list必须都是Number的子类
* @param list
*/
public void get1(List<? extends Number>  list){
System.out.println(list.size());
}
/**
* list必须都是String的父类
* @param list
*/
public void get2(List<? super String>  list){
System.out.println(list.size());
}
}

posted @ 2017-11-10 16:46 杨军威 阅读(106) | 评论 (0)编辑 收藏

秒杀系统架构优化思路

     摘要: 一、秒杀业务为什么难做1)im系统,例如qq或者微博,每个人都读自己的数据(好友列表、群列表、个人信息);2)微博系统,每个人读你关注的人的数据,一个人读多个人的数据;3)秒杀系统,库存只有一份,所有人会在集中的时间读和写这些数据,非常多个人同时读一个数据。 例如:小米手机每周二的秒杀,可能手机只有1万部,但瞬时进入的流量可能是几百几千万。又例如:12306抢票,票是有限的,库存一份,瞬...  阅读全文

posted @ 2017-11-06 17:35 杨军威 阅读(176) | 评论 (0)编辑 收藏

设计模式之jdk的动态代理

jdk的动态代理对象和目标对象要实现同一个接口。
public class Classes implements Serializable{
private Long cid;
public Long getCid() {
return cid;
}
public void setCid(Long cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
private String cname;
private String description;
}
public interface ClassesDao {
public void saveClasses(Classes classes);
}
public class ClassesDaoImpl implements ClassesDao{
@Override
public void saveClasses(Classes classes) {
System.out.println("保存");
}
}
public class MyTransaction {
public void beginTransaction(){
System.out.println("开始事务");
}
public void commit(){
System.out.println("提交事务");
}
}
public class ClassesDaoInterceptor implements InvocationHandler{
private Object target;
private MyTransaction myTransaction;
public ClassesDaoInterceptor(Object target,MyTransaction myTransaction){
this.target = target;
this.myTransaction = myTransaction;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println(proxy.getClass().getName());
if(method.getName().equals("saveClasses")||
method.getName().equals("updateClasses")){
this.myTransaction.beginTransaction();//֪ͨ
method.invoke(this.target, args);//Ŀ�귽��
this.myTransaction.commit();
}else{
method.invoke(this.target, args);
}
return null;
}
}
public class ClassesDaoTest {
public static void testSaveClasses(){
Object target = new ClassesDaoImpl();
MyTransaction myTransaction = new MyTransaction();
ClassesDaoInterceptor interceptor = new ClassesDaoInterceptor(target, myTransaction);
ClassesDao proxyDao = (ClassesDao) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), interceptor);
Classes classes = new Classes();
classes.setCname("aaaa");
proxyDao.saveClasses(classes);
}
public static void main(String[] args) {
testSaveClasses();
}
}
spring的事务也是动态代理实现的,当一个服务类里的一个实现了服务接口的方法中调用另一个服务方法,第二个服务方法不会加入到事务中,因为这种调用方式不是被代理对象调用,而是实际目标对象调用,不会产生代理对象,所以第二个服务方法不会加入到事务中,如果想实现这种操作,需要先得到aop的代理对象,AopContext.currentProxy();,得到服务接口,进行调用服务方法。spring的事务代理是cglib实现的,只能代理访问接口中的方法。

posted @ 2017-09-14 15:49 杨军威 阅读(131) | 评论 (0)编辑 收藏

设计模式之cglib的动态代理

cglib的动态生成的代理对象是目标类的子类。
public class Classes implements Serializable{
private Long cid;
public Long getCid() {
return cid;
}
public void setCid(Long cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
private String cname;
private String description;
}
public interface ClassesDao {
public void saveClasses(Classes classes);
}
public class ClassesDaoImpl implements ClassesDao{
@Override
public void saveClasses(Classes classes) {
System.out.println("保存");
}
}
public class ClassesDaoInterceptor implements MethodInterceptor {
private Object target;
private MyTransaction myTransaction;
public ClassesDaoInterceptor(Object target, MyTransaction myTransaction) {
this.target = target;
this.myTransaction = myTransaction;
}
public Object create() {
Enhancer en = new Enhancer();
en.setSuperclass(target.getClass());
en.setCallback(this);
return en.create();
}
@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy arg3) throws Throwable {
System.out.println(proxy.getClass().getName());
System.out.println(arg3.getSuperName());
if (method.getName().equals("saveClasses")
|| method.getName().equals("updateClasses")) {
this.myTransaction.beginTransaction();// ֪ͨ
method.invoke(this.target, args);// Ŀ�귽��
this.myTransaction.commit();
} else {
method.invoke(this.target, args);
}
return null;
}
}
public class MyTransaction {
public void beginTransaction(){
System.out.println("开始事务");
}
public void commit(){
System.out.println("提交事务");
}
}
public class ClassesDaoTest {
public static void testSaveClasses(){
Object dao = new ClassesDaoImpl();
MyTransaction myTransaction = new MyTransaction();
ClassesDaoInterceptor interceptor = new ClassesDaoInterceptor(dao, myTransaction);
ClassesDaoImpl proxyDao= (ClassesDaoImpl) interceptor.create();
Classes classes = new Classes();
classes.setCname("aaaa");
proxyDao.saveClasses(classes);
}
public static void main(String[] args) {
testSaveClasses();
}
}

posted @ 2017-09-14 15:41 杨军威 阅读(123) | 评论 (0)编辑 收藏

设计模式之模拟jdk的动态代理

jdk的动态代理模式的目标类和动态生成的代理类都要实现同一个接口。
public interface MoveAble {
void move();
}
public interface InvocationHandler {
public void invoke(Object o, Method m);
}
public class Tank1 implements MoveAble{
@Override
public void move() {
System.out.println("moving");
}
}
public class TimeHandler implements InvocationHandler{
private Object target;
public TimeHandler(Object target) {
super();
this.target = target;
}
@Override
public void invoke(Object o, Method m) {
long start = System.currentTimeMillis();
System.out.println("starttime:" + start);
System.out.println(o.getClass().getName());
try {
m.invoke(target);
} catch (Exception e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("time:" + (end-start));
}
}
public class Proxy {
public static Object newProxyInstance(Class infce, InvocationHandler invocationHandler) throws Exception { //JDK6 Complier API, CGLib, ASM
String methodStr = "";
String rt = "\r\n";
Method[] methods = infce.getMethods();
for(Method m : methods) {
Class<?> returnType = m.getReturnType();
methodStr += "@Override" + rt + 
"public  "+returnType+" " + m.getName() + "() {" + rt +
"    try {" + rt +
"    Method md = " + infce.getName() + ".class.getMethod(\"" + m.getName() + "\");" + rt +
"    h.invoke(this, md);" + rt +
"    }catch(Exception e) {e.printStackTrace();}" + rt +
"}";
}
String src = 
"package proxy.tank;" +  rt +
"import java.lang.reflect.Method;" + rt +
"public class $Proxy1 implements " + infce.getName() + "{" + rt +
"    public $Proxy1(InvocationHandler h) {" + rt +
"        this.h = h;" + rt +
"    }" + rt +
"    proxy.tank.InvocationHandler h;" + rt +
methodStr +
"}";
String fileName = 
"d:/src/proxy/tank/$Proxy1.java";
File f = new File(fileName);
FileWriter fw = new FileWriter(f);
fw.write(src);
fw.flush();
fw.close();
//compile
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);
Iterable units = fileMgr.getJavaFileObjects(fileName);
CompilationTask t = compiler.getTask(null, fileMgr, null, null, null, units);
t.call();
fileMgr.close();
//load into memory and create an instance
URL[] urls = new URL[] {new URL("file:/" + "d:/src/")};
URLClassLoader ul = new URLClassLoader(urls);
Class c = ul.loadClass("proxy.tank.$Proxy1");
System.out.println(c);
Constructor ctr = c.getConstructor(InvocationHandler.class);
Object m = ctr.newInstance(invocationHandler);
return m;
}
}
public class Client {
public static void main(String[] args) throws Exception {
Tank1 t = new Tank1();
InvocationHandler h = new TimeHandler(t);
MoveAble m = (MoveAble)Proxy.newProxyInstance(MoveAble.class, h);
m.move();
}
}

posted @ 2017-09-14 15:35 杨军威 阅读(122) | 评论 (0)编辑 收藏

设计模式之静态代理

public interface MoveAble {
void move();
}
public class Tank1 implements MoveAble{
@Override
public void move() {
System.out.println("moving");
}
}
/**
 * 
 * 聚合
 *
 */
public class TankTime3 implements MoveAble{
private MoveAble t;
public TankTime3(){}
public TankTime3(MoveAble t){
this.t=t;
}
@Override
public void move() {
long s = System.currentTimeMillis();
t.move();
long e = System.currentTimeMillis();
System.out.println(e-s);
}
}
public class Test {
public static void main(String[] args) {
Tank1 t =new Tank1();
TankTime3 tt = new TankTime3(t);
tt.move();
}
}

posted @ 2017-09-14 15:27 杨军威 阅读(131) | 评论 (0)编辑 收藏

设计模式之策略模式

使用策略模式自定义对象排序和比较属性值排序的例子
/**
 * 
 * 实体类的接口
 *
 */
public interface DongWu {
public int getAge();
public void setAge(int age) ;
public int getHigh();
public void setHigh(int high) ;
}
/**
 * 
 * 排序接口
 *
 */
public interface MyComparator  {
int comparatorTo(Object object);
}
/**
 * 
 * 具体的排序接口,和具体的实体类对象无关
 *
 */
public interface TypeComparator  {
int comparatorTo(Object object1,Object object2);
}
/**
 * 
 * 按照年纪倒叙排序
 *
 */
public class AgeDescTypeComparator implements TypeComparator {
@Override
public int comparatorTo(Object object1, Object object2) {
DongWu c1 = (DongWu) object1;
DongWu dw = (DongWu) object2;
if (c1.getAge() > dw.getAge()) {
return -1;
} else if (c1.getAge() < dw.getAge()) {
return 1;
}
return 0;
}
}
/**
 * 
 * 按照年纪正叙排序
 *
 */
public class AgeTypeComparator implements TypeComparator {
@Override
public int comparatorTo(Object object1, Object object2) {
DongWu c1 = (DongWu) object1;
DongWu dw = (DongWu) object2;
if (c1.getAge() > dw.getAge()) {
return 1;
} else if (c1.getAge() < dw.getAge()) {
return -1;
}
return 0;
}
}
public class Cat implements MyComparator,DongWu{
private int age;
private int high;
private TypeComparator typeComparator =new AgeDescTypeComparator();
public Cat(){}
public Cat(int age){
this.age=age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getHigh() {
return high;
}
public void setHigh(int high) {
this.high = high;
}
@Override
public int comparatorTo(Object object) {
DongWu cat = (DongWu) object;
return typeComparator.comparatorTo(this, cat);
}
}
public class Dog implements MyComparator,DongWu{
private int age;
private int high;
private TypeComparator typeComparator =new AgeDescTypeComparator();
public Dog(){}
public Dog(int age){
this.age=age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getHigh() {
return high;
}
public void setHigh(int high) {
this.high = high;
}
@Override
public int comparatorTo(Object object) {
DongWu d = (DongWu) object;
return typeComparator.comparatorTo(this, d);
}
}
public class DataSorter {
public static void sort(MyComparator[] arr){
for (int i = arr.length; i >0 ; i--) {
for(int j=0;j<i-1;j++){
MyComparator m1=arr[j];
MyComparator m2= arr[j+1];
if(m1.comparatorTo(m2)==1){
swap(arr,j,j+1);
}
}
}
}
private static void swap(Object[] arr, int j, int i) {
Object temp =arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}

posted @ 2017-09-13 11:06 杨军威 阅读(108) | 评论 (0)编辑 收藏

设计模式之Iterator

public interface Iterator {
Object next();
boolean hasNext();
}
public interface Collection {
void add(Object data);
int size();
Iterator iterator();
}
//集合
public class MyArrayList implements Collection{
private Object[] array = new Object[10];
private int index=0;//数值当前可以放值的下标
public void add( Object obj){
if(index==array.length){
Object[] newArray = new Object[array.length*2];
System.arraycopy(array, 0, newArray, 0, index);
array=newArray;
}
array[index]=obj;
index++;
}
public int size(){
return index;
}
@Override
public Iterator iterator() {
return new Aaa();
}
private class Aaa implements Iterator{
private int c=0;
@Override
public boolean hasNext() {
if(c<index){
return true;
}else{
return false;
}
}
@Override
public Object next() {
Object object = array[c];
c++;
return object;
}
}
public static void main(String[] args) {
MyArrayList arr = new MyArrayList();
for (int i = 0; i < 20; i++) {
arr.add(new Object());
}
System.out.println(arr.size());
Iterator iterator = arr.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
//链表
public class MyNode {
private Object data;
private MyNode nextNode;
public MyNode(Object data,MyNode nextNode){
this.data=data;
this.nextNode=nextNode;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public MyNode getNextNode() {
return nextNode;
}
public void setNextNode(MyNode nextNode) {
this.nextNode = nextNode;
}
}
public class MyLinkTable implements Collection{
private MyNode head;
private MyNode tail;
private int size = 0;
public void add(Object data) {
MyNode n = new MyNode(data, null);
if (head == null) {
head = n;
tail = n;
}
tail.setNextNode(n);
tail = n;
size++;
}
public int size() {
return size;
}
public MyNode getHead() {
return head;
}
public void setHead(MyNode head) {
this.head = head;
}
public MyNode getTail() {
return tail;
}
public void setTail(MyNode tail) {
this.tail = tail;
}
@Override
public Iterator iterator() {
return new Aaa();
}
private class Aaa implements Iterator{
private int c=0;
MyNode node=null;
@Override
public boolean hasNext() {
for (int i = 0; i <=c; i++) {
if(i==0){
node = head;
}else{
node = node.getNextNode();
}
}
if(node==null){
return false;
}else{
return true;
}
}
@Override
public Object next() {
for (int i = 0; i <=c; i++) {
if(i==0){
node = head;
}else{
node = node.getNextNode();
}
}
c++;
return node;
}
}
public static void main(String[] args) {
MyLinkTable node = new MyLinkTable();
node.add(1);
node.add(2);
node.add(3);
Iterator iterator = node.iterator();
while(iterator.hasNext()){
MyNode node1= (MyNode) iterator.next();
System.out.println(node1.getData());
}
}
}

posted @ 2017-09-12 15:54 杨军威 阅读(111) | 评论 (0)编辑 收藏

设计模式之装饰者模式

装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
public interface ICake {
public float cost();
}
public abstract class CakeDecorator implements ICake{
}
public class MilkCake implements ICake{
@Override
public float cost() {
return 100f;
}
}
public class Berry extends CakeDecorator {
private ICake cake;
public Berry(ICake cake) {
this.cake = cake;
}
@Override
public float cost() {
float berryPrice = 5f;
return cake.cost() + berryPrice;
}
}
public class Chocolate extends CakeDecorator{
private ICake cake;
public Chocolate(ICake cake) {
this.cake = cake;
}
@Override
public float cost() {
float chocolatePrice = 25f;
return cake.cost() + chocolatePrice;
}
}
public class Test {
public static void main(String[] args) throws FileNotFoundException {
MilkCake mc = new MilkCake();
Berry b = new Berry(mc);
Chocolate c = new Chocolate(b);
System.out.println("" + c.cost());
}
}

posted @ 2017-09-08 10:36 杨军威 阅读(100) | 评论 (0)编辑 收藏

设计模式之观察者模式

观察者模式(有时又被称为发布(publish )-订阅(Subscribe)模式、模型-视图(View)模式、源-收听者(Listener)模式或从属者模式)是软件设计模式的一种。在此种模式中,一个目标物件管理所有相依于它的观察者物件,并且在它本身的状态改变时主动发出通知。这通常透过呼叫各观察者所提供的方法来实现。此种模式通常被用来实现事件处理系统。
public interface Observer {
public void update(int low,int heigh,String weather);
void removeSubject();
}
public interface Subject {
public void registerObserver(Observer observer);
public void removeObserver(Observer observer);
public void notifyObserver();
}
public class Android implements Observer{
public Android(){}
private Subject subject;
public Android(Subject subject) {
this.subject = subject;
this.subject.registerObserver(this);
}
@Override
public void update(int low, int heigh, String weather) {
System.out.println("Android" + low + "," + heigh + "," + weather);
}
public void removeSubject() {
subject.removeObserver(this);
}
}
public class IPad implements Observer{
private Subject subject;
public IPad(){}
public IPad(Subject subject) {
this.subject = subject;
subject.registerObserver(this);
}
@Override
public void update(int low, int heigh, String weather) {
System.out.println("IPad " + low + "," + heigh + "," + weather);
}
public void removeSubject() {
subject.removeObserver(this);
}
}
public class WeatherData implements Subject{
private int low;
private int heigh;
private String weather;
private List<Observer> observerList = new ArrayList<Observer>();
public void setData(int low,int heigh,String weather) {
this.low = low;
this.heigh = heigh;
this.weather = weather;
notifyObserver();
}
public int getLow() {
return low;
}
public int getHeigh() {
return heigh;
}
public String getWeather() {
return weather;
}
@Override
public void registerObserver(Observer observer) {
if(!observerList.contains(observer)) {
observerList.add(observer);
}
}
@Override
public void removeObserver(Observer observer) {
if(observerList.contains(observer)) {
observerList.remove(observer);
}
}
@Override
public void notifyObserver() {
for(Observer o : observerList) {
o.update(getLow(), getHeigh(), getWeather());
}
}
}
public class Test {
public static void main(String[] args) {
WeatherData wd = new WeatherData();
Android android = new Android(wd);
//android.removeSubject();
IPad ipad = new IPad(wd);
//ipad.removeSubject();
wd.setData(2, 23, "---");
}
}

posted @ 2017-09-08 10:09 杨军威 阅读(132) | 评论 (0)编辑 收藏

仅列出标题
共43页: First 上一页 5 6 7 8 9 10 11 12 13 下一页 Last 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜