public class JavaLanguage implements ILanguages { @Override public void out() { System.out.println("JavaLanguage--------------"); } }
public class PythonLanguage implements ILanguages { @Override public void out() { System.out.println("PythonLanguage--------------"); } }
public class LanaguageFactory { public ILanguages create(Class<?extends ILanguages> clsName){ try { if (null != clsName){ return clsName.newInstance(); } }catch (Exception e){ e.printStackTrace(); } return null; } }
public class Test { public static void main(String[] args){ System.out.println("pattern----------------start"); ILanguages language = new LanaguageFactory().create(PythonLanguage.class); language.out(); System.out.println("pattern----------------end"); } }
public class JavaLanguage implements ILanguages { @Override public void out() { System.out.println("JavaLanguage--------------"); } }
public class PythonLanguage implements ILanguages { @Override public void out() { System.out.println("PythonLanguage--------------"); } }
public interface ILanaguageFactory { ILanguages create(); }
public class JavaLanguageFactory implements ILanaguageFactory { @Override public ILanguages create() { return new JavaLanguage(); } }
public class PythonLanguageFactory implements ILanaguageFactory { @Override public ILanguages create() { return new PythonLanguage(); } }
public class Test { public static void main(String[] args){ System.out.println("pattern----------------start"); ILanaguageFactory languageFactory = new JavaLanguageFactory(); ILanguages languages = languageFactory.create(); languages.out(); System.out.println("pattern----------------end"); } }
public interface IFile { void setParams(); } public interface IMethod { void setValue(); } public abstract class LanguageFactory { public void init(){ System.out.println("初始化"); }
protected abstract IFile createFile();
protected abstract IMethod createMethod(); } ....................................................... public class JavaFile implements IFile{ @Override public void setParams() { System.out.println("JavaFile-----setParams"); } } public class JavaMethod implements IMethod{ @Override public void setValue() { System.out.println("JavaMethod-----setValue"); } } public class JavaLanguageFactory extends LanguageFactory {
@Override protected IFile createFile() { super.init(); return new JavaFile(); }
@Override protected IMethod createMethod() { super.init(); return new JavaMethod(); } ....................................................... public class PythonFile implements IFile { @Override public void setParams() { System.out.println("PythonFile-----setParams"); } } public class PythonMethod implements IMethod { @Override public void setValue() { System.out.println("PythonMethod-----setValue"); } } public class PythonLanguageFactory extends LanguageFactory {
@Override protected IFile createFile() { super.init(); return new PythonFile(); }
@Override protected IMethod createMethod() { super.init(); return new PythonMethod(); } } ....................................................... public class Test { public static void main(String[] args){ System.out.println("pattern----------------start"); LanguageFactory factory = new JavaLanguageFactory(); factory.createFile().setParams(); factory.createMethod().setValue(); System.out.println("pattern----------------end"); } }
handles.finish(passHandle); if (obj != null && handles.lookupException(passHandle) == null && desc.hasReadResolveMethod()) { //通过反射获取ReadResolve对象,这个就是我们单例中readResolve返回的对象 Object rep = desc.invokeReadResolve(obj); if (unshared && rep.getClass().isArray()) { rep = cloneArray(rep); } //如果跟newInstance的对象不一样,就赋值给obj,返回,这个就不时新创建新的对象了。 if (rep != obj) { // Filter the replacement object if (rep != null) { if (rep.getClass().isArray()) { filterCheck(rep.getClass(), Array.getLength(rep)); } else { filterCheck(rep.getClass(), -1); } } handles.setObject(passHandle, obj = rep); } }
return obj; }
private Object checkResolve(Object obj) throws IOException { if (!enableResolve || handles.lookupException(passHandle) != null) { return obj; } Object rep = resolveObject(obj); if (rep != obj) { // The type of the original object has been filtered but resolveObject // may have replaced it; filter the replacement's type if (rep != null) { if (rep.getClass().isArray()) { filterCheck(rep.getClass(), Array.getLength(rep)); } else { filterCheck(rep.getClass(), -1); } } handles.setObject(passHandle, rep); } return rep; }
ThreadLocal单例
保证线程内部的全局唯一,且天生线程安全。但是在不同的线程,肯定是不同的。
1 2 3 4 5 6 7 8 9 10 11 12 13
public class ThreadLocalSingleton { public static ThreadLocalSingleton getInstance(){ return threadLocalInstance.get(); } private ThreadLocalSingleton(){} private static final ThreadLocal<ThreadLocalSingleton> threadLocalInstance = new ThreadLocal<ThreadLocalSingleton>(){ @Override protected ThreadLocalSingleton initialValue() { return new ThreadLocalSingleton(); } }; }
测试:
1 2 3 4 5 6 7 8
public class ThreadLocalSingletonTest { //在主线程 public static void main(String[] args){ System.out.println(ThreadLocalSingleton.getInstance()); System.out.println(ThreadLocalSingleton.getInstance()); System.out.println(ThreadLocalSingleton.getInstance()); } }
public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); }
public class LanguageBean implements Cloneable , Serializable { public String id; public String name; public String nickName; public List<String> method;
public interface Target { int request1(); int request2(); }
public abstract class Adapter implements Target { protected Adaptee adaptee; public Adapter(Adaptee adaptee){ this.adaptee = adaptee; }
public int request1(){ return 0; } public int request2(){ return 0; } }
public class Adaptee { public int specificRequest(){ return 220; } }
public class Test { public static void main(String[] args){ System.out.println("pattern----------------start"); Target adapter = new Adapter(new Adaptee()); adapter.request1(); adapter.request2(); System.out.println("pattern----------------end"); } }
public class Person implements IPerson { @Override public void findLove() { System.out.println("漂亮"); } }
public class PersonProxy implements IPerson{ private Person person; public PersonProxy(Person person){ this.person = person; } @Override public void findLove() { System.out.println("找人"); person.findLove(); System.out.println("成功");
} }
public static void main(String[] args){ PersonProxy personProxy = new PersonProxy(new Person()); personProxy.findLove(); }
public void before(){ System.out.println("before proxy is called"); } public void after(){ System.out.println("after proxy is called"); } }
测试:
1 2 3 4 5 6 7 8 9 10 11
public class Test { public static void main(String[] args){ JdkProxy personProxy = new JdkProxy(); IPerson person1 = personProxy.getInstance(new Person1()); person1.findLove();
final Class<?>[] intfs = interfaces.clone(); final SecurityManager sm = System.getSecurityManager(); if (sm != null) { checkProxyAccess(Reflection.getCallerClass(), loader, intfs); }
/* * Look up or generate the designated proxy class. */ Class<?> cl = getProxyClass0(loader, intfs);
/* * Invoke its constructor with the designated invocation handler. */ try { if (sm != null) { checkNewProxyPermission(Reflection.getCallerClass(), cl); }
final Constructor<?> cons = cl.getConstructor(constructorParams); final InvocationHandler ih = h; if (!Modifier.isPublic(cl.getModifiers())) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { cons.setAccessible(true); return null; } }); } //这里会带哦用Proxy的构造方法,并把h赋值给InvocationHandler return cons.newInstance(new Object[]{h}); } catch (IllegalAccessException|InstantiationException e) { throw new InternalError(e.toString(), e); } }
public class GiftInfo { public String name; public GiftInfo(String name){ this.name = name; } }
public class QualifyService { public boolean qualify(GiftInfo giftInfo){ System.out.println(giftInfo.name + "10积分"); return true; } }
public class PayService { public boolean pay(GiftInfo giftInfo){ System.out.println("支付"+giftInfo.name + "积分成功"); return true; } }
public class ShippingService { public String delivery(GiftInfo giftInfo){ System.out.println(giftInfo.name + "快递中"); return "666"; } }
//门面 public class FacadeService { private QualifyService qualifyService = new QualifyService(); private PayService payService = new PayService(); private ShippingService shippingService = new ShippingService();
public void exchange(GiftInfo giftInfo){ if (qualifyService.qualify(giftInfo)){ if (payService.pay(giftInfo)){ System.out.println(shippingService.delivery(giftInfo)); } } } }
public static void main(String[] args){ System.out.println("pattern----------------start"); FacadeService facadeService = new FacadeService(); facadeService.exchange(new GiftInfo("礼物信息")); System.out.println("pattern----------------end"); }
public abstract class CourseComponet { public void addChild(CourseComponet componet){ throw new UnsupportedOperationException("不支持添加"); } public void removeChild(CourseComponet componet){ throw new UnsupportedOperationException("不支持删除"); } public String getName(CourseComponet componet){ throw new UnsupportedOperationException("不支持获取名称"); } public double getPrice(CourseComponet componet){ throw new UnsupportedOperationException("不支持获取价格"); } public void print(){ throw new UnsupportedOperationException("不支持打印"); } }
public class Course extends CourseComponet { private String name; private double price; public Course(String name, double price){ this.name = name; this.price = price; }
@Override public String getName(CourseComponet componet) { return this.name; }
@Override public double getPrice(CourseComponet componet) { return this.price; }
@Override public void print() { System.out.println(this.name+":"+this.price+"元"); } }
public class CoursePackage extends CourseComponet{ private List<CourseComponet> items = new ArrayList<>(); private String name; private Integer level; public CoursePackage(String name, int level){ this.name = name; this.level = level; }
@Override public void addChild(CourseComponet componet) { items.add(componet); }
@Override public void removeChild(CourseComponet componet) { items.remove(componet); }
@Override public String getName(CourseComponet componet) { return this.name; }
@Override public void print() { System.out.println(this.name); for (CourseComponet courseComponet :items){ if (this.level != null){ for (int i=0;i<this.level;i++){ System.out.print(" "); }
for (int i=0;i<this.level;i++){ if (i == 0){ System.out.print("+"); } System.out.print("-"); } } courseComponet.print(); }
} }
测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public static void main(String[] args){ System.out.println("===================透明组合模式=============="); CourseComponet java = new Course("Java",2000); CourseComponet ai = new Course("ai",8000); CourseComponet coursePackage = new CoursePackage("架构师",2);
CourseComponet python = new Course("python",6000); CourseComponet css = new Course("css",3000);
public interface IMessage { void sendMessage(String msg,String toUser); } public class EmailMessage implements IMessage{ @Override public void sendMessage(String msg, String toUser) { System.out.println("邮件发送内容:"+msg+" 给谁"+toUser); } } public class SmsMessage implements IMessage{ @Override public void sendMessage(String msg, String toUser) { System.out.println("SMS发送内容:"+msg+" 给谁"+toUser); } }
public class NormalMessage extends AbastractMessage{ public NormalMessage(IMessage message) { super(message); } } //紧急消息 public class UrgencyMessage extends AbastractMessage{ public UrgencyMessage(IMessage message) { super(message); }
public abstract class AbastractMessage { private IMessage message; public AbastractMessage(IMessage message){ this.message = message; }
public void sendMessage(String msg, String toUser) { this.message.sendMessage(msg,toUser); } }
测试:
1 2 3 4 5 6 7 8 9 10 11 12 13
public static void main(String[] args){
IMessage message = new SmsMessage(); AbastractMessage abastractMessage = new NormalMessage(message); abastractMessage.sendMessage("加班申请","王老板"); System.out.println("===================普通==============");
message = new EmailMessage(); abastractMessage = new UrgencyMessage(message); abastractMessage.sendMessage("加班申请","王老板"); System.out.println("===================加急==============");
//老板发任务 public class Boos { public void command(String task,Leader leader){ leader.doing(task); } } //代理着经理分配任务,啥事不干 public class Leader implements IEmployee { private Map<String,IEmployee> employees = new HashMap<>(); public Leader(){ employees.put("Banner",new EmplyeeA()); employees.put("List",new EmplyeeB()); } @Override public void doing(String task) { /*if ("Banner".equals(task)){ new EmplyeeA().doing(task); } else if ("List".equals(task)){ new EmplyeeB().doing(task); }else{ System.out.println("这个任务"+task+"做不了,人手不够"); }*/
if (!employees.containsKey(task)){ System.out.println("这个任务"+task+"做不了,人手不够"); return; } employees.get(task).doing(task); } }
//员工 public interface IEmployee { void doing(String task); } public class EmplyeeA implements IEmployee { protected String goodAt = "Banner"; @Override public void doing(String task) { System.out.println("我是员工A,擅长 "+ goodAt +",接受工作"+task); } } public class EmplyeeB implements IEmployee { protected String goodAt = "List"; @Override public void doing(String task) { System.out.println("我是员工B,擅长 "+ goodAt +",接受工作"+task); } }
测试:
1 2 3 4 5 6 7
public class Test { public static void main(String[] args){ new Boos().command("Banner",new Leader()); new Boos().command("List",new Leader()); new Boos().command("Ad",new Leader()); } }
public abstract class AbastractCourse { public final void createCourse(){ //发布预习资料 postPreResource(); //制作课件 createPPT(); //直播授课 liveVideo(); //上传课后资料 postResource(); // 布置作业 postWork(); if (needCheckWork()){ checkWork(); } }
public abstract class Payment { public abstract String getPayName(); public MsgResult pay(String uid,double amount){ if (queryBalance(uid) < amount){ return new MsgResult(500,"支付失败","余额不足"); } return new MsgResult(200,"支付成功","订单金额:"+amount);
public class AliPay extends Payment { @Override public String getPayName() { return "支付宝"; } @Override protected double queryBalance(String uid) { return 5000; } }
public class JDPay extends Payment { @Override public String getPayName() { return "京东"; } @Override protected double queryBalance(String uid) { return 6000; } }
public class WechatPay extends Payment { @Override public String getPayName() { return "微信"; } @Override protected double queryBalance(String uid) { return 100; } }
public class UnionPay extends Payment { @Override public String getPayName() { return "银联"; } @Override protected double queryBalance(String uid) { return 10000; } } //这里其实用到了委派模式 public class PayStrategy { public static final String ALI_PAY="AliPay"; public static final String WECHAT_PAY="WechatPay"; public static final String JD_PAY="JDPay"; public static final String UNION_PAY="UnionPay"; public static final String DEFAULT_PAY=ALI_PAY; private static Map<String,Payment> payStrategy = new HashMap<>(); static { payStrategy.put(ALI_PAY,new AliPay()); payStrategy.put(WECHAT_PAY,new WechatPay()); payStrategy.put(JD_PAY,new JDPay()); payStrategy.put(UNION_PAY,new UnionPay()); } public static Payment get(String payKey){ if (!payStrategy.containsKey(payKey)){ return payStrategy.get(DEFAULT_PAY); } return payStrategy.get(payKey); } }
public class Order { public String uid; public String orderId; public double amount; public Order(String uid, String orderId,double amount){ this.uid = uid; this.orderId = orderId; this.amount = amount; } public MsgResult pay(){ return pay(PayStrategy.DEFAULT_PAY); } public MsgResult pay(String payKey){ Payment payment = PayStrategy.get(payKey); System.out.println("支付方式:"+payment.getPayName()); System.out.println("交易金额:"+this.amount); return payment.pay(uid,amount); } }
public class MsgResult { public int code; public Object data; public String msg; public MsgResult(int code,String msg,Object data){ this.code = code; this.data = data; this.msg = msg; }
public class Test { public static void main(String[] args){ System.out.println("pattern----------------start"); Order order = new Order("1","12392847283753",230.87); System.out.println(order.pay()); System.out.println(order.pay(PayStrategy.WECHAT_PAY)); System.out.println("pattern----------------end"); } }
public class Member { public String loginName; public String loginPass; public String roleName; public Member(String loginName,String loginPass){ this.loginName = loginName; this.loginPass = loginPass; } }
public abstract class Handler<T> { protected Handler next; public void next(Handler next){ this.next = next; }; public abstract void doHandler(Member member);
//建造者模式 public static class Builder<T> { private Handler<T> head; private Handler<T> tail; public Builder<T> addHandler(Handler<T> handler){ if (this.head == null){ this.head = this.tail = handler; return this; } this.tail.next(handler); this.tail = handler; return this; } public Handler<T> build(){ return this.head; } } }
public class ValidateHandler extends Handler { @Override public void doHandler(Member member) { if(StringUtils.isEmpty(member.loginName) || StringUtils.isEmpty(member.loginPass)){ System.out.println("用户名或密码为空"); return; } System.out.println("用户名或密码不为空,往下执行"); next.doHandler(member); } }
public class LoginHandler extends Handler { @Override public void doHandler(Member member) { System.out.println("登录成功"); member.roleName = "管理员"; System.out.println("用户名或密码不为空,往下执行"); next.doHandler(member); } }
public class AuthHandler extends Handler{ @Override public void doHandler(Member member) { if(!"管理员".equals(member.roleName)){ System.out.println("你不是管理员,不能操作"); return; } System.out.println("允许操作"); } }
public class MemberChain { public void login(String loginName,String loginPass){ //通用模式
/*ValidateHandler validateHandler = new ValidateHandler(); LoginHandler loginHandler = new LoginHandler(); AuthHandler authHandler = new AuthHandler(); validateHandler.next(loginHandler); loginHandler.next(authHandler); validateHandler.doHandler(new Member(loginName,loginPass));*/
public class Test { public static void main(String[] args) { System.out.println("pattern----------------start"); MemberChain memberChain = new MemberChain(); memberChain.login("tim","123"); System.out.println("pattern----------------end"); } }
public interface Iterator<E> { E next(); boolean hasNext(); } public class IteratorImpl<E> implements Iterator<E>{ private List<E> list; private int cursor; private E element;
public IteratorImpl( List<E> list){ this.list= list; }
@Override public E next() { System.out.println("当前位置:"+cursor); element = list.get(cursor); cursor++; return element; }
@Override public boolean hasNext() { if (cursor > list.size()-1){ return false; } return true; } }
public interface ICourseAggreagte { void add(Course course); void remove(Course course); Iterator<Course> iterator(); } public class CourseAggreagteImpl implements ICourseAggreagte { private List courseList; public CourseAggreagteImpl(){ this.courseList = new ArrayList(); } @Override public void add(Course course) { courseList.add(course); }
@Override public void remove(Course course) { courseList.remove(course); }
@Override public Iterator<Course> iterator() { return new IteratorImpl<Course>(courseList); } }
public class Course { public String name; public Course(String name){ this.name = name; } }
public class Test { public static void main(String[] args) { System.out.println("pattern----------------start"); Course java = new Course("java"); Course py = new Course("python"); Course js = new Course("js"); Course ai = new Course("ai");
ICourseAggreagte aggreagte = new CourseAggreagteImpl(); aggreagte.add(java); aggreagte.add(py); aggreagte.add(js); aggreagte.add(ai);
public interface ICommand { void execute(); } public class PlayCommand implements ICommand{ private Gplayer gplayer; public PlayCommand(Gplayer gplayer){ this.gplayer = gplayer; } @Override public void execute() { this.gplayer.paly(); } } public class PauseCommand implements ICommand{ private Gplayer gplayer; public PauseCommand(Gplayer gplayer){ this.gplayer = gplayer; } @Override public void execute() { this.gplayer.pause(); } }
public class SpeedCommand implements ICommand{ private Gplayer gplayer; public SpeedCommand(Gplayer gplayer){ this.gplayer = gplayer; } @Override public void execute() { this.gplayer.speed(); } } public class StopCommand implements ICommand{ private Gplayer gplayer; public StopCommand(Gplayer gplayer){ this.gplayer = gplayer; } @Override public void execute() { this.gplayer.stop(); } }
//播放器 public class Gplayer { public void paly(){ System.out.println("播放"); } public void speed(){ System.out.println("滑动"); } public void stop(){ System.out.println("停止"); } public void pause(){ System.out.println("暂停"); } } //控制条?人 public class Controller { private List<ICommand> commons = new ArrayList<>(); public void execute(ICommand command){ command.execute(); }
public void addCommond(ICommand command){ commons.add(command); } public void executes(){ for(ICommand command: commons){ command.execute(); } commons.clear(); } }
测试:
1 2 3 4 5 6 7 8 9 10 11 12 13
public static void main(String[] args){ System.out.println("pattern----------------start"); Gplayer gplayer = new Gplayer(); Controller controller = new Controller(); controller.execute(new PlayCommand(gplayer)); System.out.println("=======执行组合擦欧总========="); controller.addCommond(new PlayCommand(gplayer)); controller.addCommond(new PauseCommand(gplayer)); controller.addCommond(new SpeedCommand(gplayer)); controller.addCommond(new StopCommand(gplayer)); controller.executes(); System.out.println("pattern----------------end"); }
public class AppContext { public static final UserState STATE_LOGIN = new LoginState(); public static final UserState STATE_UNLOGIN = new UnLoginState(); private UserState currentUserState = STATE_UNLOGIN;
//快照,备忘录 public class ArticleMemento { public String title; public String content; public String imgs; public ArticleMemento(String title,String content,String imgs){ this.title = title; this.content = content; this.imgs = imgs; }
//草稿箱 public class DraftsBox { //容器,存文章快照:压栈 private final Stack<ArticleMemento> stack = new Stack<>(); public void addMemento(ArticleMemento articleMemento){ stack.push(articleMemento); } public ArticleMemento getMemento(){ return stack.pop(); } }
//发起人 public class Editor { public String title; public String content; public String imgs; public Editor(String title,String content,String imgs){ this.title = title; this.content = content; this.imgs = imgs; } public ArticleMemento saveToMemento(){ ArticleMemento articleMemento = new ArticleMemento(this.title,this.content,this.imgs); return articleMemento; } public void undoFromMenento(ArticleMemento articleMemento){ this.title = articleMemento.title; this.content = articleMemento.content; this.imgs = articleMemento.imgs; }
public class User { public String name; private ChatRoom chatRoom; public User(String name,ChatRoom chatRoom){ this.name = name; this.chatRoom = chatRoom; } public void sendMessage(String msg){ this.chatRoom.showMessage(this,msg); } } //中介者 public class ChatRoom { public void showMessage(User user,String msg){ System.out.println("["+user.name+"]"+msg); } }
public static void main(String[] args){ System.out.println("pattern----------------start"); ChatRoom chatRoom = new ChatRoom(); User zhang = new User("漳卅",chatRoom); User li = new User("里斯",chatRoom); zhang.sendMessage("你好,里斯"); li.sendMessage("你好,漳卅"); System.out.println("pattern----------------end"); }