枚举例题源码,反射例题源码,模板与装饰器模式例题源码

枚举例题:
package cn.itcast_02;

/*
* 通过JDK5提供的枚举来做枚举类
*/
public enum Direction {
FRONT, BEHIND, LEFT, RIGHT;
}


---------------------------------------
package cn.itcast_02;

/*
* 通过JDK5提供的枚举来做枚举类
*/
public enum Direction2 {
FRONT("前"), BEHIND("后"), LEFT("左"), RIGHT("右");

private String name;

private Direction2(String name) {
this.name = name;
}

public String getName() {
return name;
}

// @Override
// public String toString() {
// return "我爱林青霞";
// }
}

---------------------------------------
package cn.itcast_02;

/*
* 通过JDK5提供的枚举来做枚举类
*/
public enum Direction3 {
FRONT("前") {
@Override
public void show() {
System.out.println("前");
}
},
BEHIND("后") {
@Override
public void show() {
System.out.println("后");
}
},
LEFT("左") {
@Override
public void show() {
System.out.println("左");
}
},
RIGHT("右") {
@Override
public void show() {
System.out.println("右");
}
};

private String name;

private Direction3(String name) {
this.name = name;
}

public String getName() {
return name;
}

public abstract void show();
}

---------------------------------------
package cn.itcast_02;

public class DirectionDemo {
public static void main(String[] args) {
Direction d = Direction.FRONT;
System.out.println(d); // FRONT
// public String toString()返回枚举常量的名称,它包含在声明中。
System.out.println("-------------");
Direction2 d2 = Direction2.FRONT;
System.out.println(d2);
System.out.println(d2.getName());
System.out.println("-------------");
Direction3 d3 = Direction3.FRONT;
System.out.println(d3);
System.out.println(d3.getName());
d3.show();
System.out.println("--------------");

Direction3 dd = Direction3.FRONT;
dd = Direction3.LEFT;

switch (dd) {
case FRONT:
System.out.println("你选择了前");
break;
case BEHIND:
System.out.println("你选择了后");
break;
case LEFT:
System.out.println("你选择了左");
break;
case RIGHT:
System.out.println("你选择了右");
break;
}
}
}
---------------------------------------
package cn.itcast_02;

public class EnumMethodDemo {
public static void main(String[] args) {
// int compareTo(E o)
Direction2 d21 = Direction2.FRONT;
Direction2 d22 = Direction2.BEHIND;
Direction2 d23 = Direction2.LEFT;
Direction2 d24 = Direction2.RIGHT;
System.out.println(d21.compareTo(d21));
System.out.println(d21.compareTo(d24));
System.out.println(d24.compareTo(d21));
System.out.println("---------------");
// String name()
System.out.println(d21.name());
System.out.println(d22.name());
System.out.println(d23.name());
System.out.println(d24.name());
System.out.println("--------------");
// int ordinal()
System.out.println(d21.ordinal());
System.out.println(d22.ordinal());
System.out.println(d23.ordinal());
System.out.println(d24.ordinal());
System.out.println("--------------");
// String toString()
System.out.println(d21.toString());
System.out.println(d22.toString());
System.out.println(d23.toString());
System.out.println(d24.toString());
System.out.println("--------------");
// <T> T valueOf(Class<T> type,String name)
Direction2 d = Enum.valueOf(Direction2.class, "FRONT");
System.out.println(d.getName());
System.out.println("----------------");
// values()
// 此方法虽然在JDK文档中查找不到,但每个枚举类都具有该方法,它遍历枚举类的所有枚举值非常方便
Direction2[] dirs = Direction2.values();
for (Direction2 d2 : dirs) {
System.out.println(d2);
System.out.println(d2.getName());
}
}
}
--------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------

模板模式源码:

模板模式:
package cn.itcast_01;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public abstract class GetTime {
// 需求:请给我计算出一段代码的运行时间
public long getTime() {
long start = System.currentTimeMillis();
// for循环
// for (int x = 0; x < 10000; x++) {
// System.out.println(x);
// }

// 视频
// try {
// BufferedInputStream bis = new BufferedInputStream(
// new FileInputStream("a.avi"));
// BufferedOutputStream bos = new BufferedOutputStream(
// new FileOutputStream("b.avi"));
// byte[] bys = new byte[1024];
// int len = 0;
// while ((len = bis.read(bys)) != -1) {
// bos.write(bys, 0, len);
// }
// bos.close();
// bis.close();
// } catch (IOException e) {
// e.printStackTrace();
// }

// 再给我测试一个代码:集合操作的,多线程操作,常用API操作的等等...
code();

long end = System.currentTimeMillis();

return end - start;
}

public abstract void code();
}
---------------------------------------
package cn.itcast_01;

public class ForDemo extends GetTime {

@Override
public void code() {
for (int x = 0; x < 100000; x++) {
System.out.println(x);
}
}

}
-----------------------------------------
package cn.itcast_01;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class IODemo extends GetTime{

@Override
public void code() {
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("a.avi"));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("b.avi"));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
------------------------------------------
具体测试类
package cn.itcast_01;

public class GetTimeDemo {
public static void main(String[] args) {
// GetTime gt = new GetTime();
// System.out.println(gt.getTime() + "毫秒");

GetTime gt = new ForDemo();
System.out.println(gt.getTime() + "毫秒");

gt = new IODemo();
System.out.println(gt.getTime() + "毫秒");
}
}
----------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------

装饰器模式源码:

package cn.itcast_02;

public interface Phone {
public abstract void call();
}
------------------------------------------
package cn.itcast_02;

public class IPhone implements Phone {

@Override
public void call() {
System.out.println("手机可以打电话了");
}

}

------------------------------------------
package cn.itcast_02;

public abstract class PhoneDecorate implements Phone {

private Phone p;

public PhoneDecorate(Phone p) {
this.p = p;
}

@Override
public void call() {
this.p.call();
}
}

------------------------------------------
package cn.itcast_02;

public class MusicPhoneDecorate extends PhoneDecorate {

public MusicPhoneDecorate(Phone p) {
super(p);
}

@Override
public void call() {
super.call();
System.out.println("手机可以听音乐");
}
}


------------------------------------------
package cn.itcast_02;

public class RingPhoneDecorate extends PhoneDecorate {

public RingPhoneDecorate(Phone p) {
super(p);
}

@Override
public void call() {
System.out.println("手机可以听彩铃");
super.call();
}
}

------------------------------------------
package cn.itcast_02;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Scanner;

public class PhoneDemo {
public static void main(String[] args) {
Phone p = new IPhone();
p.call();
System.out.println("------------");

// 需求:我想在接电话前,听彩铃
PhoneDecorate pd = new RingPhoneDecorate(p);
pd.call();
System.out.println("------------");

// 需求:我想在接电话后,听音乐
pd = new MusicPhoneDecorate(p);
pd.call();
System.out.println("------------");

// 需求:我要想手机在接前听彩铃,接后听音乐
// 自己提供装饰类,在打电话前听彩铃,打电话后听音乐
pd = new RingPhoneDecorate(new MusicPhoneDecorate(p));
pd.call();
System.out.println("----------");
// 想想我们在IO流中的使用
// InputStream is = System.in;
// InputStreamReader isr = new InputStreamReader(is);
// BufferedReader br = new BufferedReader(isr);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter((new OutputStreamWriter(
System.out)));

Scanner sc = new Scanner(System.in);
}
}
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------

反射源码赏析:

package cn.itcast_01;

public class Person {
private String name;
int age;
public String address;

public Person() {
}

private Person(String name) {
this.name = name;
}

Person(String name, int age) {
this.name = name;
this.age = age;
}

public Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}

public void show() {
System.out.println("show");
}

public void method(String s) {
System.out.println("method " + s);
}

public String getString(String s, int i) {
return s + "---" + i;
}

private void function() {
System.out.println("function");
}

@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", address=" + address
+ "]";
}

}

package cn.itcast_01;

/*
* 反射:就是通过class文件对象,去使用该文件中的成员变量,构造方法,成员方法。
*
* Person p = new Person();
* p.使用
*
* 要想这样使用,首先你必须得到class文件对象,其实也就是得到Class类的对象。
* Class类:
* 成员变量 Field
* 构造方法 Constructor
* 成员方法 Method
*
* 获取class文件对象的方式:
* A:Object类的getClass()方法
* B:数据类型的静态属性class
* C:Class类中的静态方法
* public static Class forName(String className)
*
* 一般我们到底使用谁呢?
* A:自己玩 任选一种,第二种比较方便
* B:开发 第三种
* 为什么呢?因为第三种是一个字符串,而不是一个具体的类名。这样我们就可以把这样的字符串配置到配置文件中。
*/
public class ReflectDemo {
public static void main(String[] args) throws ClassNotFoundException {
// 方式1
Person p = new Person();
Class c = p.getClass();

Person p2 = new Person();
Class c2 = p2.getClass();

System.out.println(p == p2);// false
System.out.println(c == c2);// true

// 方式2
Class c3 = Person.class;
// int.class;
// String.class;
System.out.println(c == c3);

// 方式3
// ClassNotFoundException
Class c4 = Class.forName("cn.itcast_01.Person");
System.out.println(c == c4);
}
}

-------------------------------------------------------------------------------
package cn.itcast_02;

import java.lang.reflect.Constructor;

import cn.itcast_01.Person;

/*
* 通过反射获取构造方法并使用。
*/
public class ReflectDemo {
public static void main(String[] args) throws Exception {
// 获取字节码文件对象
Class c = Class.forName("cn.itcast_01.Person");

// 获取构造方法
// public Constructor[] getConstructors():所有公共构造方法
// public Constructor[] getDeclaredConstructors():所有构造方法
// Constructor[] cons = c.getDeclaredConstructors();
// for (Constructor con : cons) {
// System.out.println(con);
// }

// 获取单个构造方法
// public Constructor<T> getConstructor(Class<?>... parameterTypes)
// 参数表示的是:你要获取的构造方法的构造参数个数及数据类型的class字节码文件对象
Constructor con = c.getConstructor();// 返回的是构造方法对象

// Person p = new Person();
// System.out.println(p);
// public T newInstance(Object... initargs)
// 使用此 Constructor 对象表示的构造方法来创建该构造方法的声明类的新实例,并用指定的初始化参数初始化该实例。
Object obj = con.newInstance();
System.out.println(obj);

// Person p = (Person)obj;
// p.show();
}
}

package cn.itcast_02;

import java.lang.reflect.Constructor;

/*
* 需求:通过反射去获取该构造方法并使用:
* public Person(String name, int age, String address)
*
* Person p = new Person("林青霞",27,"北京");
* System.out.println(p);
*/
public class ReflectDemo2 {
public static void main(String[] args) throws Exception {
// 获取字节码文件对象
Class c = Class.forName("cn.itcast_01.Person");

// 获取带参构造方法对象
// public Constructor<T> getConstructor(Class<?>... parameterTypes)
Constructor con = c.getConstructor(String.class, int.class,
String.class);

// 通过带参构造方法对象创建对象
// public T newInstance(Object... initargs)
Object obj = con.newInstance("林青霞", 27, "北京");

System.out.println(obj);
}
}

package cn.itcast_02;

import java.lang.reflect.Constructor;

/*
* 需求:通过反射获取私有构造方法并使用
* private Person(String name){}
*
* Person p = new Person("风清扬");
* System.out.println(p);
*/
public class ReflectDemo3 {
public static void main(String[] args) throws Exception {
// 获取字节码文件对象
Class c = Class.forName("cn.itcast_01.Person");

// 获取私有构造方法对象
// NoSuchMethodException:每个这个方法异常
// 原因是一开始我们使用的方法只能获取公共的,下面这种方式就可以了。
Constructor con = c.getDeclaredConstructor(String.class);

// 用该私有构造方法创建对象
// IllegalAccessException:非法的访问异常。
// 暴力访问
con.setAccessible(true);// 值为true则指示反射的对象在使用时应该取消Java语言访问检查。
Object obj = con.newInstance("风清扬");

System.out.println(obj);
}
}
-------------------------------------------------------------------------------
package cn.itcast_03;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/*
* 通过发生获取成员变量并使用
*/
public class ReflectDemo {
public static void main(String[] args) throws Exception {
// 获取字节码文件对象
Class c = Class.forName("cn.itcast_01.Person");

// 获取所有的成员变量
// Field[] fields = c.getFields();
// Field[] fields = c.getDeclaredFields();
// for (Field field : fields) {
// System.out.println(field);
// }

/*
* Person p = new Person(); p.address = "北京"; System.out.println(p);
*/

// 通过无参构造方法创建对象
Constructor con = c.getConstructor();
Object obj = con.newInstance();
System.out.println(obj);

// 获取单个的成员变量
// 获取address并对其赋值
Field addressField = c.getField("address");
// public void set(Object obj,Object value)
// 将指定对象变量上此 Field 对象表示的字段设置为指定的新值。
addressField.set(obj, "北京"); // 给obj对象的addressField字段设置值为"北京"
System.out.println(obj);

// 获取name并对其赋值
// NoSuchFieldException
Field nameField = c.getDeclaredField("name");
// IllegalAccessException
nameField.setAccessible(true);
nameField.set(obj, "林青霞");
System.out.println(obj);

// 获取age并对其赋值
Field ageField = c.getDeclaredField("age");
ageField.setAccessible(true);
ageField.set(obj, 27);
System.out.println(obj);
}
}

-------------------------------------------------------------------------------
package cn.itcast_04;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class ReflectDemo {
public static void main(String[] args) throws Exception {
// 获取字节码文件对象
Class c = Class.forName("cn.itcast_01.Person");

// 获取所有的方法
// Method[] methods = c.getMethods(); // 获取自己的包括父亲的公共方法
// Method[] methods = c.getDeclaredMethods(); // 获取自己的所有的方法
// for (Method method : methods) {
// System.out.println(method);
// }

Constructor con = c.getConstructor();
Object obj = con.newInstance();

/*
* Person p = new Person(); p.show();
*/

// 获取单个方法并使用
// public void show()
// public Method getMethod(String name,Class<?>... parameterTypes)
// 第一个参数表示的方法名,第二个参数表示的是方法的参数的class类型
Method m1 = c.getMethod("show");
// obj.m1(); // 错误
// public Object invoke(Object obj,Object... args)
// 返回值是Object接收,第一个参数表示对象是谁,第二参数表示调用该方法的实际参数
m1.invoke(obj); // 调用obj对象的m1方法

System.out.println("----------");
// public void method(String s)
Method m2 = c.getMethod("method", String.class);
m2.invoke(obj, "hello");
System.out.println("----------");

// public String getString(String s, int i)
Method m3 = c.getMethod("getString", String.class, int.class);
Object objString = m3.invoke(obj, "hello", 100);
System.out.println(objString);
// String s = (String)m3.invoke(obj, "hello",100);
// System.out.println(s);
System.out.println("----------");

// private void function()
Method m4 = c.getDeclaredMethod("function");
m4.setAccessible(true);
m4.invoke(obj);
}
}

-------------------------------------------------------------------------------
-------------------------------------------------------------------------------

动态代理源码:
package cn.itcast_06;

public interface StudentDao {
public abstract void login();

public abstract void regist();
}

package cn.itcast_06;

public class StudentDaoImpl implements StudentDao {

@Override
public void login() {
System.out.println("登录功能");
}

@Override
public void regist() {
System.out.println("注册功能");
}

}

package cn.itcast_06;

/*
* 用户操作接口
*/
public interface UserDao {
public abstract void add();

public abstract void delete();

public abstract void update();

public abstract void find();
}

package cn.itcast_06;

public class UserDaoImpl implements UserDao {

@Override
public void add() {
System.out.println("添加功能");
}

@Override
public void delete() {
System.out.println("删除功能");
}

@Override
public void update() {
System.out.println("修改功能");
}

@Override
public void find() {
System.out.println("查找功能");
}

}

package cn.itcast_06;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler {
private Object target; // 目标对象

public MyInvocationHandler(Object target) {
this.target = target;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("权限校验");
Object result = method.invoke(target, args);
System.out.println("日志记录");
return result; // 返回的是代理对象
}
}


package cn.itcast_06;

import java.lang.reflect.Proxy;

public class Test {
public static void main(String[] args) {
UserDao ud = new UserDaoImpl();
ud.add();
ud.delete();
ud.update();
ud.find();
System.out.println("-----------");
// 我们要创建一个动态代理对象
// Proxy类中有一个方法可以创建动态代理对象
// public static Object newProxyInstance(ClassLoader loader,Class<?>[]
// interfaces,InvocationHandler h)
// 我准备对ud对象做一个代理对象
MyInvocationHandler handler = new MyInvocationHandler(ud);
UserDao proxy = (UserDao) Proxy.newProxyInstance(ud.getClass()
.getClassLoader(), ud.getClass().getInterfaces(), handler);
proxy.add();
proxy.delete();
proxy.update();
proxy.find();
System.out.println("-----------");

StudentDao sd = new StudentDaoImpl();
MyInvocationHandler handler2 = new MyInvocationHandler(sd);
StudentDao proxy2 = (StudentDao) Proxy.newProxyInstance(sd.getClass()
.getClassLoader(), sd.getClass().getInterfaces(), handler2);
proxy2.login();
proxy2.regist();
}
}

 

你可能感兴趣的:(装饰器模式)