(1)、继承 Thread 类:但 Thread 本质上也是实现了 Runnable 接口的一个实例,它代表一个线程的实例,并且,启动线程的唯一方法就是通过 Thread 类的 start()实例方法。
public class MyThread extends Thread {
public void run() {
System.out.println("MyThread.run()");
}
}
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
myThread1.start();
myThread2.start();
public class MyThread implements Runnable {
public void run() {
System.out.println("MyThread.run()");
}
}
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.start();
package com.hy.多线程高并发;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
/**
* 有返回值的线程
*/
@SuppressWarnings("unchecked")
public class E {
public static void main(String[] args) throws ExecutionException,
InterruptedException {
System.out.println("----程序开始运行----");
Date date1 = new Date();
int taskSize = 5;
// 创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
// 创建多个有返回值的任务
List list = new ArrayList();
for (int i = 0; i < taskSize; i++) {
Callable c = new MyCallable(i + " ");
// 执行任务并获取 Future 对象
Future f = pool.submit(c);
// System.out.println(">>>" + f.get().toString());
list.add(f);
}
// 关闭线程池
pool.shutdown();
// 获取所有并发任务的运行结果
for (Future f : list) {
// 从 Future 对象上获取任务的返回值,并输出到控制台
System.out.println(">>>" + f.get().toString());
}
Date date2 = new Date();
System.out.println("----程序结束运行----,程序运行时间【"
+ (date2.getTime() - date1.getTime()) + "毫秒】");
}
}
class MyCallable implements Callable
package com.hy.多线程高并发;
public class Counter {
private volatile int count = 0;
public void inc() {
try {
Thread.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
@Override
public String toString() {
return "[count=" + count + "]";
}
}
package com.hy.多线程高并发;
public class VolatileTest {
public static void main(String[] args) {
final Counter counter = new Counter();
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
counter.inc();
}
}).start();
}
System.out.println(counter);
}
}
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(4);
ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(4);
ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
官方对线程池的执行过程描述如下:
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
package com.hy.多线程高并发;
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
/*
* permits the initial number of permits available. This value may be negative,
in which case releases must occur before any acquires will be granted.
fair true if this semaphore will guarantee first-in first-out granting of
permits under contention, else false
*/
static Semaphore semaphore = new Semaphore(5, true);
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
test();
}
}).start();
}
}
public static void test() {
try {
//申请一个请求
semaphore.acquire();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "进来了");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "走了");
//释放一个请求
semaphore.release();
}
}
package com.hy.多线程高并发;
import java.util.concurrent.Semaphore;
public class ThreadCommunication {
private static int num;
/**
* * 定义一个信号量,该类内部维持了多个线程锁,可以阻塞多个线程,释放多个线程,
* 线程的阻塞和释放是通过 permit 概念来实现的
* * 线程通过 semaphore.acquire()方法获取 permit,如果当前 semaphore 有 permit 则分配给该线程,
* 如果没有则阻塞该线程直到 semaphore
* * 调用 release()方法释放 permit。
* * 构造函数中参数:permit(允许) 个数,
*
*/
private static Semaphore semaphore = new Semaphore(0);
public static void main(String[] args) {
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
try {
//模拟耗时操作之后初始化变量 num
Thread.sleep(1000);
num = 1;
//初始化完参数后释放两个 permit
semaphore.release(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
try {
//获取 permit,如果 semaphore 没有可用的 permit 则等待,如果有则消耗一个
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "获取到 num 的值为:" + num);
}
});
Thread threadC = new Thread(new Runnable() {
@Override
public void run() {
try {
//获取 permit,如果 semaphore 没有可用的 permit 则等待,如果有则消耗一个
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "获取到 num 的值为:" + num);
}
});
//同时开启 3 个线程
threadA.start();
threadB.start();
threadC.start();
}
}
package com.hy.多线程高并发;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Description:
* 同一个类中的 2 个方法都加了同步锁,多个线程能同时访问同一个类中的这两个方法吗?
这个问题需要考虑到Lock与synchronized 两种实现锁的不同情形。因为这种情况下使用Lock 和synchronized
会有截然不同的结果。Lock 可以让等待锁的线程响应中断,Lock 获取锁,之后需要释放锁。如下代码,多个线程不可
访问同一个类中的 2 个加了 Lock 锁的方法
* @return:
* @Author: Hy
* @Date: 2020
*/
public class qq {
private int count = 0; //初始化一个变量
private Lock lock = new ReentrantLock();//设置 lock 锁
//方法 1
public Runnable run1 = new Runnable() {
public void run() {
lock.lock(); //加锁
while (count < 1000) {
try {
//打印是否执行该方法
System.out.println(Thread.currentThread().getName() +
" run1: " + count++);
} catch (Exception e) {
e.printStackTrace();
}
}
lock.unlock(); //解锁
}
};
//方法 2
public Runnable run2 = new Runnable() {
public void run() {
lock.lock(); //上锁
while (count < 1000) {
try {
System.out.println(Thread.currentThread().getName() +
" run2: " + count++);
} catch (Exception e) {
e.printStackTrace();
}
}
lock.unlock(); //解锁
}
};
public static void main(String[] args) {
qq t = new qq(); //创建一个对象
new Thread(t.run1).start();//获取该对象的方法 1
new Thread(t.run2).start();//获取该对象的方法 2
}
}
package com.hy.多线程高并发;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Description:
* 而 synchronized 却不行,使用 synchronized 时
* 当我们访问同一个类对象的时候,是同一把锁,所以可以访问
* 该对象的其他 synchronized 方法。代码如下:
* @Param:
* @return:
* @Author: Hy
* @Date: 2020
*/
public class qq1 {
private int count = 0; //初始化一个变量
private Lock lock = new ReentrantLock();//设置 lock 锁
//方法 1
public Runnable run1 = new Runnable() {
public void run() {
//我们上锁下
synchronized (this){ //设置关键字 synchronized,以当前类为锁
while (count < 1000) {
try {
//打印是否执行该方法
System.out.println(Thread.currentThread().getName() +
" run1: " + count++);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
//方法 2
public Runnable run2 = new Runnable() {
public void run() {
synchronized (this){ //设置关键字 synchronized,以当前类为锁
while (count < 1000) {
try {
System.out.println(Thread.currentThread().getName() +
" run2: " + count++);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
public static void main(String[] args) {
qq1 t = new qq1(); //创建一个对象
new Thread(t.run1).start();//获取该对象的方法 1
new Thread(t.run2).start();//获取该对象的方法 2
}
}
package com.hy.多线程高并发.产生死锁的例子;
/**
* @Description: /**
* 一个简单的死锁类
* 当 DeadLock 类的对象 flag==1 时(td1),先锁定 o1,睡眠 500 毫秒
* 而 td1 在睡眠的时候另一个 flag==0 的对象(td2)线程启动,先锁定 o2,睡眠 500 毫秒
* td1 睡眠结束后需要锁定 o2 才能继续执行,而此时 o2 已被 td2 锁定;
* td2 睡眠结束后需要锁定 o1 才能继续执行,而此时 o1 已被 td1 锁定;
* td1、td2 相互等待,都需要得到对方锁定的资源才能继续执行,从而死锁。
* @return:
* @Author: Hy
* @Date: 2020
*/
public class DeadLock implements Runnable {
public int flag = 1;
//静态对象是类的所有对象共享的
private static Object o1 = new Object(), o2 = new Object();
public void run() {
System.out.println("flag=" + flag);
if (flag == 1) {
synchronized (o1) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println("1");
}
}
}
if (flag == 0) {
synchronized (o2) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println("0");
}
}
}
}
public static void main(String[] args) {
DeadLock td1 = new DeadLock();
DeadLock td2 = new DeadLock();
td1.flag = 1;
td2.flag = 0;
//td1,td2 都处于可执行状态,但 JVM 线程调度先执行哪个线程是不确定的。
//td2 的 run()可能在 td1 的 run()之前运行
new Thread(td1).start();
new Thread(td2).start();
}
}
1)加锁顺序(线程按照一定的顺序加锁)
package com.hy.多线程高并发.如何避免死锁.加锁顺序;
public class DeadLock {
public int flag = 1;
//静态对象是类的所有对象共享的
private static Object o1 = new Object(), o2 = new Object();
public void money(int flag) {
this.flag = flag;
if (flag == 1) {
synchronized (o1) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println("当前的线程是" +
Thread.currentThread().getName() + " " + "flag 的值" + "1");
}
}
}
if (flag == 0) {
synchronized (o2) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println("当前的线程是" +
Thread.currentThread().getName() + " " + "flag 的值" + "0");
}
}
}
}
public static void main(String[] args) {
final DeadLock td1 = new DeadLock();
final DeadLock td2 = new DeadLock();
td1.flag = 1;
td2.flag = 0;
//td1,td2 都处于可执行状态,但 JVM 线程调度先执行哪个线程是不确定的。
//td2 的 run()可能在 td1 的 run()之前运行
final Thread t1 = new Thread(new Runnable() {
public void run() {
td1.flag = 1;
td1.money(1);
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
//让 t2 等待 t1 执行完
t1.join();//核心代码,让 t1 执行完后 t2 才会执行
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
td2.flag = 0;
td1.money(0);
}
});
t2.start();
}
}
package com.hy.多线程高并发.如何避免死锁.加锁时限;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class DeadLock {
public int flag = 1;
//静态对象是类的所有对象共享的
private static Object o1 = new Object(), o2 = new Object();
public void money(int flag) throws InterruptedException {
this.flag = flag;
if (flag == 1) {
synchronized (o1) {
Thread.sleep(500);
synchronized (o2) {
System.out.println("当前的线程是" +
Thread.currentThread().getName() + " " + "flag 的值" + "1");
}
}
}
if (flag == 0) {
synchronized (o2) {
Thread.sleep(500);
synchronized (o1) {
System.out.println("当前的线程是" +
Thread.currentThread().getName() + " " + "flag 的值" + "0");
}
}
}
}
public static void main(String[] args) {
final Lock lock = new ReentrantLock();
final DeadLock td1 = new DeadLock();
final DeadLock td2 = new DeadLock();
td1.flag = 1;
td2.flag = 0;
//td1,td2 都处于可执行状态,但 JVM 线程调度先执行哪个线程是不确定的。
//td2 的 run()可能在 td1 的 run()之前运行
final Thread t1 = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
String tName = Thread.currentThread().getName();
td1.flag = 1;
try {
//获取不到锁,就等 5 秒,如果 5 秒后还是获取不到就返回 false
if (lock.tryLock(5000, TimeUnit.MILLISECONDS)) {
System.out.println(tName + "获取到锁!");
} else {
System.out.println(tName + "获取不到锁!");
return;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
td1.money(1);
} catch (Exception e) {
System.out.println(tName + "出错了!!!");
} finally {
System.out.println("当前的线程是" + Thread.currentThread().getName() + "释放锁!!");
lock.unlock();
}
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
public void run() {
String tName = Thread.currentThread().getName();
// TODO Auto-generated method stub
td1.flag = 1;
try {
//获取不到锁,就等 5 秒,如果 5 秒后还是获取不到就返回 false
if (lock.tryLock(5000, TimeUnit.MILLISECONDS)) {
System.out.println(tName + "获取到锁!");
} else {
System.out.println(tName + "获取不到锁!");
return;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
td2.money(0);
} catch (Exception e) {
System.out.println(tName + "出错了!!!");
} finally {
System.out.println("当前的线程是" + Thread.currentThread().getName() + "释放锁!!");
lock.unlock();
}
}
});
t2.start();
}
}
package com.hy.多线程高并发;
public class MySignal {
//共享的变量
private boolean hasDataToProcess = false;
//取值
public boolean getHasDataToProcess() {
return hasDataToProcess;
}
//存值
public void setHasDataToProcess(boolean hasDataToProcess) {
this.hasDataToProcess = hasDataToProcess;
}
public static void main(String[] args) {
//同一个对象
final MySignal my = new MySignal();
//线程 1 设置 hasDataToProcess 值为 true
final Thread t1 = new Thread(new Runnable() {
public void run() {
my.setHasDataToProcess(true);
}
});
t1.start();
//线程 2 取这个值 hasDataToProcess
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
//等待线程 1 完成然后取值
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
my.getHasDataToProcess();
System.out.println("t1 改变以后的值:" + my.isHasDataToProcess());
}
});
t2.start();
}
//定义一个方法
private boolean isHasDataToProcess() {
return hasDataToProcess;
}
}
package com.hy.多线程高并发;
//资源类
class Resource {
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name) {
//生产资源
while (flag) {
try {
//线程等待。消费者消费资源
wait();
} catch (Exception e) {
}
}
this.name = name + "---" + count++;
System.out.println(Thread.currentThread().getName() + "...生产者..." + this.name);
flag = true;
//唤醒等待中的消费者
this.notifyAll();
}
public synchronized void out() {
//消费资源
while (!flag) {
//线程等待,生产者生产资源
try {
wait();
} catch (Exception e) {
}
}
System.out.println(Thread.currentThread().getName() + "...消费者..." + this.name);
flag = false;
//唤醒生产者,生产资源
this.notifyAll();
}
}
//生产者
class Producer implements Runnable {
private Resource res;
Producer(Resource res) {
this.res = res;
}
//生产者生产资源
public void run() {
while (true) {
res.set("商品");
}
}
}
//消费者消费资源
class Consumer implements Runnable {
private Resource res;
Consumer(Resource res) {
this.res = res;
}
public void run() {
while (true) {
res.out();
}
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) {
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
t1.start();
t2.start();
}
}
class Outer {
class Inner {}
public static void foo() {
new Inner();
}
public void bar() {
new Inner();
}
public static void main(String[] args) {
new Inner();
}
}
new Outer().new Inner();
Java 中 的 反 射 首 先 是 能 够 获 取 到 Java 中 要 反 射 类 的 字 节 码 , 获 取 字 节 码 有 三 种 方 法
final List list = new ArrayList();
List proxyInstance =
(List)Proxy.newProxyInstance(list.getClass().getClassLoader(),
list.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(list, args);
}
});
proxyInstance.add("你好");
System.out.println(list);
package javase高级.反射;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
public class Test1 {
public static void main(String[] args) {
ArrayList list = new ArrayList<>();
List proxyInstance = (List) Proxy.newProxyInstance(list.getClass().getClassLoader(),
list.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(list,args);
}
});
proxyInstance.add("周元");
System.out.println(list);
}
}
静态代理通常只代理一个类,动态代理是代理一个接口下的多个实现类。
静态代理事先知道要代理的是什么,而动态代理不知道要代理什么东西,只有在运行时才知道。
package javase高级.设计模式.单例模式;
//饿汉式
public class Singleton {
//直接创建对象
private static Singleton instance = new Singleton();
//私有化构造函数
private Singleton(){
}
//返回对象实例
public static Singleton getInstance(){
return instance;
}
}
package javase高级.设计模式.单例模式;
//懒汉式
public class Singleton1 {
//声明变量
private static volatile Singleton1 singleton1 = null;
//私有构造函数
private Singleton1(){
}
//提供对外的方法,这种更加装逼。。
public static Singleton1 getInstance(){
if (singleton1 == null){
synchronized (Singleton1.class){
if (singleton1 == null){
singleton1 = new Singleton1();
}
}
}
return singleton1;
}
}
package javase高级.设计模式.工厂模式.普通工厂模式;
interface Sender{
public Sender Send();
}
class MailSender implements Sender{
@Override
public Sender Send() {
System.out.println("来自地狱的一封信~~");
return null;
}
}
class SMSender implements Sender{
@Override
public Sender Send() {
System.out.println("坚强的存活下去吧");
return null;
}
}
//我们建一个工厂
class SendFactory{
public Sender produce(String type){
if ("mail".equals(type)){
return new MailSender().Send();
}else if ("sms".equals(type)){
return new SMSender().Send();
}else {
System.out.println("请输入正确类型");
return null;
}
}
}
public class Test {
public static void main(String[] args) {
SendFactory sendFactory = new SendFactory();
sendFactory.produce("mail");
sendFactory.produce("sms");
}
}
package javase高级.设计模式.工厂模式.多个工厂方法模式;
interface Sender{
public Sender Send();
}
class MailSender implements Sender{
@Override
public Sender Send() {
System.out.println("花开花落花满天");
return null;
}
}
class SMSender implements Sender{
@Override
public Sender Send() {
System.out.println("落花无情");
return null;
}
}
class SendFactory{
public Sender produceMail(){
return new MailSender();
}
public Sender produceSms(){
return new SMSender();
}
}
public class FactoryTest {
public static void main(String[] args) {
SendFactory factory = new SendFactory();
Sender sender = factory.produceMail();
sender.Send();
}
}
package javase高级.设计模式.工厂模式.静态工厂方法模式;
interface Sender{
public Sender Send();
}
class MailSender implements Sender {
@Override
public Sender Send() {
System.out.println("花开花落花满天");
return null;
}
}
class SMSender implements Sender {
@Override
public Sender Send() {
System.out.println("落花无情");
return null;
}
}
class SendFactory{
//静态方法
public static Sender produceMail(){
return new MailSender();
}
//静态方法
public static Sender produceSms(){
return new SMSender();
}
}
public class FactoryTest {
public static void main(String[] args) {
Sender sender = SendFactory.produceMail(); //不需要new,直接调用即可
sender.Send();
}
}
package javase高级.设计模式.工厂模式.最优解抽象工厂模式;
interface Sender{
public void send();
}
interface Provider{
public Sender produce();
}
class MailSender implements Sender{
@Override
public void send() {
System.out.println("上穷碧落下黄泉");
}
}
class SmsSender implements Sender{
@Override
public void send() {
System.out.println("可悲之人,用情之深足以惊天地泣鬼神");
}
}
//工厂一
class SendSmsFactory implements Provider{
@Override
public Sender produce() { //返回一个对象
return new SmsSender();
}
}
//工厂二
class SendMailFactory implements Provider{
@Override
public Sender produce() { //返回一个对象
return new MailSender();
}
}
public class Test {
public static void main(String[] args) {
Provider provider = new SendMailFactory();
Sender produce = provider.produce();
produce.send();
}
}
package javase高级.设计模式.建造者模式;
import java.util.ArrayList;
import java.util.List;
interface Sender{
public void send();
}
interface Provider{
public Sender produce();
}
class MailSender implements Sender{
@Override
public void send() {
System.out.println("上穷碧落下黄泉");
}
}
class SmsSender implements Sender{
@Override
public void send() {
System.out.println("可悲之人,用情之深足以惊天地泣鬼神");
}
}
//其实建造者模式就是前面抽象工厂模式和最后的 Test 结合起来得到的。
class Builder{
private List list = new ArrayList();
public void produceMailSender(int count){
for (int i = 0;i < count;i++){
list.add(new MailSender());
}
}
public void produceSmsSender(int count){
for (int i = 0;i < count;i++){
list.add(new SmsSender());
}
}
}
public class TestBuilder {
public static void main(String[] args) {
Builder builder = new Builder();
builder.produceSmsSender(3);
}
}
package javase高级.设计模式.适配器设计模式.类的适配器模式;
class Source{
public void method1(){
System.out.println("这是原始的方法~~");
}
}
interface Targetable{
//与原来类中的方法相同
public void method1();
public void method2();
}
class Adapter extends Source implements Targetable{
@Override
public void method2() {
System.out.println("这是目标方法~~");
}
}
public class AdapterTest {
public static void main(String[] args) {
Adapter adapter = new Adapter();
adapter.method1();
adapter.method2();
}
}
package javase高级.设计模式.适配器设计模式.对象的适配器模式;
import com.sun.xml.internal.bind.v2.model.core.Adapter;
/**
* @Description:
* 基本思路和类的适配器模式相同
* 只是将 Adapter 类作修改,这次不继承 Source 类
* 而是持有 Source 类的实例,以达到解决兼容性的问题。
* @Param:
* @return:
* @Author: Hy
* @Date: 2020
*/
class Source{
public void method1(){
System.out.println("这是原始的方法~~");
}
}
interface Targetable{
//与原来类中的方法相同
public void method1();
public void method2();
}
class Wrapper implements Targetable{
private Source source;
public Wrapper(Source source) {
super();
this.source = source;
}
@Override
public void method1() {
source.method1();
}
@Override
public void method2() {
System.out.println("这是目标方法~~");
}
}
public class AdapterTest {
public static void main(String[] args) {
Source source = new Source();
Wrapper adapter = new Wrapper(source);
adapter.method1();
adapter.method2();
}
}
package javase高级.设计模式.装饰模式;
interface Sourceable{
public void method();
}
class Source implements Sourceable{
@Override
public void method() {
System.out.println("原始方法~~");
}
}
//再写一个类
class Decorator implements Sourceable{
private Sourceable sourceable;
public Decorator(Sourceable sourceable) {
this.sourceable = sourceable;
}
@Override
public void method() {
System.out.println("装饰之前~~");
sourceable.method();
System.out.println("装饰之后~~");
}
}
public class DecoratorTest {
public static void main(String[] args) {
Sourceable sourceable = new Source();
Decorator decorator = new Decorator(sourceable);
decorator.method();
}
}
策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。
需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无, 属于辅助类),提供辅助函数。
策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种算法做封装。
因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。
package javase高级.设计模式.策略模式;
interface ICalculator{
public int calculate(String exp);
}
class AbstractCalculator{
public int[] split(String exp,String opt){
String array[] = exp.split(opt);
int arrayInt[] = new int[2];
arrayInt[0] = Integer.parseInt(array[0]);
arrayInt[1] = Integer.parseInt(array[1]);
return arrayInt;
}
}
//定义一个减法
class Minus extends AbstractCalculator implements ICalculator{
@Override
public int calculate(String exp) {
int arrayInt[] = split(exp,"-");
return arrayInt[0] - arrayInt[1];
}
}
//定义一个加法
class Plus extends AbstractCalculator implements ICalculator{
@Override
public int calculate(String exp) {
int arrayInt[] = split(exp,"\\+");
return arrayInt[0] + arrayInt[1];
}
}
public class StrategyTest {
public static void main(String[] args) {
String exp = "2+8";
ICalculator cal = new Plus();
int result = cal.calculate(exp);
System.out.println(result);
}
}
package javase高级.设计模式.观察者模式;
import java.util.Enumeration;
import java.util.Vector;
interface Observer{
public void update();
}
class Observer1 implements Observer{
@Override
public void update() {
System.out.println("观察者1,正在思考");
}
}
class Observer2 implements Observer{
@Override
public void update() {
System.out.println("观察者2,正在思考");
}
}
interface Subject{
//增加观察者
public void add(Observer observer);
//删除观察者
public void del(Observer observer);
//通知所有观察者
public void notifyObservers();
//自身的操作
public void operation();
}
//我们重写一下几个方法
abstract class AbstractSubject implements Subject{
//这里我们使用线程安全的一个集合,存放一下
private Vector vector = new Vector();
@Override
public void add(Observer observer) {
vector.add(observer);
}
@Override
public void del(Observer observer) {
vector.remove(observer);
}
@Override
public void notifyObservers() {
Enumeration enumo = vector.elements();
while (enumo.hasMoreElements()){
enumo.nextElement().update();
}
}
}
class MySubject extends AbstractSubject{
@Override
public void operation() {
System.out.println("更新一下" +
":-------");
notifyObservers();
}
}
public class ObserverTest {
public static void main(String[] args) {
MySubject mySubject = new MySubject();
mySubject.add(new Observer1());
mySubject.add(new Observer2());
mySubject.operation();
}
}