public class Student {
public static final Student student = new Student();
private Student(){}
public static Student getInstance(){
return student;
}
}
//测试
Student instance = Student.getInstance();
Student instance1 = Student.getInstance();
//测试的结果是两次获取的对象都是同一个
System.out.println(instance1.hashCode());
System.out.println(instance.hashCode());
public class Employee {
public static Employee employee = null;
private Employee(){}
public static Employee getInstance(){
if(employee == null){
employee = new Employee();
}
return employee;
}
}
public class Employee {
public static Employee employee = null;
private Employee(){}
public static Employee getInstance(){
if(employee == null){
synchronized (Employee.class){
employee = new Employee();
}
}
return employee;
}
}
public class Employee {
public static Employee employee = null;
private Employee(){}
public static Employee getInstance(){
if(employee == null){
synchronized (Employee.class){
if(employee == null){
employee = new Employee();
}
}
}
return employee;
}
}
enum Teacher {
INSTANCE;
}
//使用
Teacher.INSTANCE
//原有类
public class Target {
//只能判断字符串是否为null
public Boolean isEmpty(String str){
return str == null;
}
}
//增强类
public class TargetDecorate extends Target {
private Target target;
public TargetDecorate(){
}
public TargetDecorate(Target target){
this.target = target;
}
//不仅能判断字符串是否为null,还能判断是否为""
@Override
public Boolean isEmpty(String str) {
Boolean empty = target.isEmpty(str);
if(!empty){
return "".equals(str);
}
return empty;
}
}
//测试
@Test
public void test1(){
TargetDecorate targetDecorate = new TargetDecorate(new Target());
System.out.println(targetDecorate.isEmpty(""));
}
public interface IPhone {
void call();
}
public class Huawei implements IPhone{
@Override
public void call(){
System.out.println("华为");
}
}
public class Xiaomi implements IPhone{
@Override
public void call(){
System.out.println("小米");
}
}
//这里的类型可以用ConcurrentHashMap来存
public class PhoneFactory {
public IPhone getPhone(String type){
if("huawei".equals(type)){
return new Huawei();
}else if("xiaomi".equals(type)){
return new Xiaomi();
}
return null;
}
}
//上面的类修改后
public class PhoneFactory {
public static ConcurrentHashMap<String,IPhone> hashMap = new ConcurrentHashMap();
static{
initHashMap();//静态代码块中的方法随着类加载而执行
}
private static void initHashMap(){
hashMap.put("huawei",new Huawei());
hashMap.put("xiaomi",new Xiaomi());
}
public IPhone getPhone(String type){
return hashMap.get(type);
}
}
@Test
public void test2(){
PhoneFactory phoneFactory = new PhoneFactory();
IPhone xiaomi = phoneFactory.getPhone("xiaomi");
IPhone huawei = phoneFactory.getPhone("huawei");
xiaomi.call();//小米
huawei.call();//华为
}
public interface IPhone {
void call();
}
public interface IPhoneFactory {
IPhone getPhone();
}
public class Huawei implements IPhone {
@Override
public void call(){
System.out.println("华为");
}
}
public class Xiaomi implements IPhone {
@Override
public void call(){
System.out.println("小米");
}
}
public class HaweiFactory implements IPhoneFactory{
@Override
public Huawei getPhone(){
return new Huawei();
}
}
public class XiaomiFactory implements IPhoneFactory {
@Override
public Xiaomi getPhone() {
return new Xiaomi();
}
}
@Test
public void test3(){
Xiaomi xiaomi = new XiaomiFactory().getPhone();
xiaomi.call();//小米
Huawei huawei = new HaweiFactory().getPhone();
huawei.call();//华为
}
public interface IPad {
public void tv();
}
public interface IPhone {
void call();
}
public interface IFactory {
IPhone getPhone();
IPad getPad();
}
public class HuaweiPhone implements IPhone {
@Override
public void call() {
System.out.println("华为");
}
}
public class HuaweiPad implements IPad {
@Override
public void tv() {
System.out.println("华为的pad");
}
}
public class XiaomiPhone implements IPhone {
@Override
public void call(){
System.out.println("小米");
}
}
public class HaweiFactory implements IFactory {
@Override
public HuaweiPhone getPhone(){
return new HuaweiPhone();
}
@Override
public IPad getPad() {
return new HuaweiPad();
}
}
public class XiaomiFactory implements IFactory{
@Override
public IPhone getPhone() {
return new XiaomiPhone();
}
@Override
public IPad getPad() {
return null;
}
}
@Test
public void test4(){
IPad huaweiPad = new HaweiFactory().getPad();
huaweiPad.tv();//华为的pad
IPhone huaweiPhone = new HaweiFactory().getPhone();
huaweiPhone.call();//华为
IPhone xiaomiPhone = new XiaomiFactory().getPhone();
xiaomiPhone.call();//小米
IPad xiaomiPad = new XiaomiFactory().getPad();
xiaomiPad.tv();//空指针,因为小米没有pad
}
public abstract class FoodPreparer {
// 模板方法
public void prepareFood() {
prepareIngredients();
cook();
serve();
}
// 步骤1:准备食材,抽象方法由子类实现
public abstract void prepareIngredients();
// 步骤2:烹饪,抽象方法由子类实现
public abstract void cook();
// 步骤3:服务/上菜,抽象方法由子类实现
public abstract void serve();
}
public class PastaPreparer extends FoodPreparer {
@Override
public void prepareIngredients() {
System.out.println("Preparing pasta ingredients.");
}
@Override
public void cook() {
System.out.println("Cooking pasta.");
}
@Override
public void serve() {
System.out.println("Serving pasta.");
}
}
public class PizzaPreparer extends FoodPreparer {
@Override
public void prepareIngredients() {
System.out.println("Preparing pizza ingredients.");
}
@Override
public void cook() {
System.out.println("Baking pizza.");
}
@Override
public void serve() {
System.out.println("Serving pizza.");
}
}
@Test
public void test() throws Exception{
FoodPreparer pastaPreparer = new PastaPreparer();
pastaPreparer.prepareFood(); // 输出准备意大利面的整个过程
System.out.println("======================");
FoodPreparer pizzaPreparer = new PizzaPreparer();
pizzaPreparer.prepareFood(); // 输出准备披萨的整个过程
}
// 目标接口:中国插座
public interface ChineseSocket {
void plugIn();
}
// 适配者类:美国插头
public class AmericanPlug {
public void connect() {
System.out.println("美国插头已连接。");
}
}
// 类适配器:美国插头适配到中国插座
public class PowerAdaptor extends AmericanPlug implements ChineseSocket {
// 适配器类不需要重写任何方法,因为它直接继承了适配者的方法,并且已经实现了目标接口
// 客户端可以通过这个适配器类来调用目标接口的方法
public void plugIn() {
// 在调用适配者的方法之前或之后,可以添加一些额外的逻辑
System.out.println("美国插头正在适配到中国插座...");
// 调用适配者的方法
connect();
// 适配成功后的额外逻辑
System.out.println("美国插头已成功适配到中国插座。");
}
}
@Test
public void test(){
// 创建适配器对象
ChineseSocket chineseSocket = new PowerAdaptor();
// 通过适配器对象调用目标接口的方法
chineseSocket.plugIn();
}
//接口
public interface ISongHua {
void songHua();
}
//被代理类
public class XiaoMing implements ISongHua{
@Override
public void songHua() {
System.out.println("小明送花给小兰");
}
}
//代理类
public class XiaoMingProxy implements ISongHua{
private XiaoMing xiaoMing;
public XiaoMingProxy() {
}
public XiaoMingProxy(XiaoMing xiaoMing) {
this.xiaoMing = xiaoMing;
}
@Override
public void songHua() {
System.out.println("送花之前的逻辑");
//送花的逻辑
xiaoMing.songHua();
System.out.println("送花之后的逻辑");
}
}
//测试
@Test
public void SongHuaTest(){
new XiaoMingProxy(new XiaoMing()).songHua();
}
//结果
送花之前的逻辑
小明送花给小兰
送花之后的逻辑
代理类
的名字通常是$Proxy后加上一个数字Class proxyClass = Proxy.getProxyClass(类加载器,类实现的接口);
System.out.println("Proxy class name: " + proxyClass.getName());
//结果:Proxy class name: 包名.$Proxy7
代理对象(实例)
的名字通常是:被代理类名@哈希码被代理类实现的接口proxy = (被代理类实现的接口) Proxy.newProxyInstance(类加载器,类实现的接口,InvocationHandler对象);
//结果:Proxy class name: 包名.被代理类@47f37ef1
//接口
interface Hello {
void sayHello();
}
//被代理类(必须实现接口)
public class SimpleHello implements Hello{
@Override
public void sayHello() {
System.out.println("Hello, world!");
}
}
//调用处理器
public class HelloInvocationHandler implements InvocationHandler {
//目标对象,也就是被代理的对象
private Object target;
public HelloInvocationHandler(Object target) {
this.target = target;
}
/**
* @param proxy 被代理的对象
* @param method 被代理对象的方法
* @param args 被代理对象方法中的参数
* @return
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("方法执行前的操作");
//调用被代理的方法,target就是被代理类的对象,args就是被代理类对象中方法的参数
Object result = method.invoke(target, args);
System.out.println("方法执行后的操作");
//原始方法的执行结果
return result;
}
}
//测试
@Test
public void JdkTest() {
// 创建目标对象
SimpleHello hello = new SimpleHello();
// 创建InvocationHandler对象,并传入目标对象
InvocationHandler handler = new HelloInvocationHandler(hello);
//创建类加载器
ClassLoader classLoader = hello.getClass().getClassLoader();
//找到类实现的接口
Class<?>[] interfaces = hello.getClass().getInterfaces();
// 创建代理对象
Hello proxy = (Hello) Proxy.newProxyInstance(classLoader, interfaces, handler);
// 调用代理对象的方法
proxy.sayHello();
}
//被代理类
public class HelloTarget {
public void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
}
//方法拦截器
public class SimpleInterceptor implements MethodInterceptor {
/**
*
* @param obj 被代理对象
* @param method 被代理对象的方法
* @param args 被代理对象方法的参数
* @param proxy cglib 代理后的方法,一般不用
* @return
*/
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("目标方法执行前操作");
// 调用目标方法:cglib代理后的方法.invokeSuper(被代理对象,被代理对象方法的参数)
Object result = proxy.invokeSuper(obj, args);
System.out.println("目标方法执行后操作");
//被代理方法返回的结果
return result;
}
}
//测试
@Test
public void CglibTest() throws Exception{
// 创建目标对象
HelloTarget target = new HelloTarget();
// 创建 Enhancer 对象,并设置目标类
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(HelloTarget.class);
// 设置回调接口
enhancer.setCallback(new SimpleInterceptor());
// 创建代理对象
HelloTarget proxy = (HelloTarget) enhancer.create();
// 调用代理对象的方法
proxy.sayHello("World");
}
//策略接口
public interface PaymentStrategy {
public double pay(double money);
}
//策略类1
public class CashPayment implements PaymentStrategy {
@Override
public double pay(double money) {
System.out.println("Cash Payment of " + money);
return money;
}
}
//策略类2
public class CardPayment implements PaymentStrategy {
@Override
public double pay(double money) {
System.out.println("Card Payment of " + money);
return money - money * 0.02; // 假设刷卡有2%的优惠
}
}
//策略上下文类
public class PaymentContext {
private PaymentStrategy strategy;
public PaymentContext(PaymentStrategy strategy){
this.strategy = strategy;
}
public double executePayment(double money){
return this.strategy.pay(money);
}
}
//测试
@Test
public void strategyTest(){
PaymentContext paymentContext = new PaymentContext(new CashPayment());
System.out.println("Cash Payment: " + paymentContext.executePayment(100));
paymentContext = new PaymentContext(new CardPayment());
System.out.println("Card Payment: " + paymentContext.executePayment(100));
}