目录
单例设计模式
懒汉模式
饿汉模式
静态内部类(推荐使用)
枚举模式
工厂方法模式
工厂方法定义
应用场景
主要优点
demo:根据反射+注释实现
抽象工厂模式
定义
应用场景
优缺点
demo
建造者模式
定义
应用场景
优缺点
demo
原型模式
定义
应用场景
优缺点
demo
享元模式
定义
应用场景
优缺点
demo
门面模式(外观模式)
定义
应用场景
优缺
demo
适配器模式
定义
应用场景
优缺点
demo
装饰器模式
定义
应用场景
优缺点
demo
策略模式
定义
应用场景
优缺点
demo
模板方法模式
定义
应用场景
优缺点
demo
观察者模式
定义
应用场景
优缺点
demo
责任链模式
定义
应用场景
优缺点
demo
public class Single_3 {
public static volatile Single_3 single_3;
public static Single_3 getInstance(){
synchronized (Single_3.class){
if (single_3 != null){
single_3 = new Single_3();
}
}
return Single_3.single_3;
}
}
public class Single_2 {
public static Single_2 single_2 = new Single_2();
public Single_2(){}
public Single_2 getInstance(){
return single_2;
}
}
public class Single_4 {
public Single_4(){
if (SingleHolder.single_4 != null){
throw new RuntimeException("单例不允许多个实例");
}
}
public static class SingleHolder{
private static Single_4 single_4 = new Single_4();
}
public static Single_4 getInstance(){
return SingleHolder.single_4;
}
}
public enum Single_5 {
INSTANCE;
public void getTest(){
}
}
public interface Shape {
void onDraw();
void getColor();
void getShape() ;
}
import com.iflytek.yws.Shape;
import com.iflytek.yws.ShapeType;
@ShapeType(channelid = 3)
public class Bar implements Shape {
@Override
@UiThread
public void onDraw() {
Log.v("YWS","--------Bar-------");
}
@Override
public void getColor() {
Log.v("YWS","--------Bar------getShape-");
}
@Override
public void getShape() {
Log.v("YWS","--------Bar------getShape-");
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ShapeType {
int channelid();
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import dalvik.system.DexFile;
public class ShapeFactoty {
public HashMap hashMap = new HashMap();
public ShapeFactoty(){
if (SingleHolder.shapeFactoty != null){
new Throwable("单例模式不允许多个创建多个实例!");
}
}
private static class SingleHolder{
private static ShapeFactoty shapeFactoty = new ShapeFactoty();
}
public static ShapeFactoty getInstance(){
return SingleHolder.shapeFactoty;
}
public Shape create(int channelId){
try {
String clazz = hashMap.get(channelId);
Class c = Class.forName(hashMap.get(channelId));
return (Shape) c.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
public void init(){
List classs = getClassName("com.iflytek.yws.shape");
for (int i = 0 ; i < classs.size() ; i++){
try {
Class theClass = Class.forName(classs.get(i));
boolean hasAnn = theClass.isAnnotationPresent(ShapeType.class);
if (hasAnn) {
// 获取该注解对象
ShapeType myAnn = (ShapeType)theClass.getAnnotation(ShapeType.class);
// 获取属性值
int id = myAnn.channelid();
hashMap.put(id,classs.get(i));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public List getClassName(String packageName){
ListclassNameList=new ArrayList();
try {
DexFile df = new DexFile(MyApplication.context.getPackageCodePath());//通过DexFile查找当前的APK中可执行文件
Enumeration enumeration = df.entries();//获取df中的元素 这里包含了所有可执行的类名 该类名包含了包名+类名的方式
while (enumeration.hasMoreElements()) {//遍历
String className = (String) enumeration.nextElement();
if (className.contains(packageName)) {//在当前所有可执行的类里面查找包含有该包名的所有类
classNameList.add(className);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classNameList;
}
}
调用实现如下:
ShapeFactoty.getInstance().create(3).getShape();
它让具体的创建实例过程与客户端分离,客户端是通过它们的抽象接口操作实例,产品的具体类名也被具体工厂的实现分离,不会出现在客户代码中。
最大的好处便是易于交换产品系列,由于具体工厂类,在一个应用中只需要在初始化的时候出现一次,这就使得改变一个应用的具体工厂变得非常容易,它只需要改变具体工厂即可使用不同产品配置
增加新的产品等级结构很复杂,需要修改抽象工厂和所有的具体工厂类,对“开闭原则”的支持呈现倾斜性
package com.iflytek.request.design.build;
import com.iflytek.request.tool.LogY;
public class RetrofitShape {
private String color;
private String shape;
private String size;
private String name;
public RetrofitShape(String color, String shape, String size, String name) {
this.color = color;
this.shape = shape;
this.size = size;
this.name = name;
}
public void doStart() {
LogY.v(toString());
}
public static final class Builder {
private String color;
private String shape;
private String size;
private String name;
public Builder() {
}
public Builder setColor(String str) {
color = str;
return this;
}
public Builder setShape(String str) {
shape = str;
return this;
}
public Builder setSize(String str) {
size = str;
return this;
}
public Builder setName(String str) {
name = str;
return this;
}
public RetrofitShape build() {
return new RetrofitShape(color, shape, size, name);
}
}
@Override
public String toString() {
return "RetrofitShape{" +
"color='" + color + '\'' +
", shape='" + shape + '\'' +
", size='" + size + '\'' +
", name='" + name + '\'' +
'}';
}
}
RetrofitShape builder = new RetrofitShape.Builder().setColor("red").setName("yjJJJJJJ").setShape("").setSize("100").build();;
builder.doStart();
package com.iflytek.request.design.prototype;
import androidx.annotation.NonNull;
public class People implements Cloneable {
public People(UserInfo userInfo, int type, int index){
this.userInfo = userInfo;
this.index = index;
this.type = type;
}
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
@NonNull
@Override
protected People clone() throws CloneNotSupportedException {
People clone = (People)super.clone();
UserInfo userInfo = this.userInfo.clone();
clone.setUserInfo(userInfo);
return clone;
// return (People)super.clone();
}
@Override
public String toString() {
return "People{" +
hashCode() + '\'' +
"userInfo=" + userInfo +
", type=" + type +
", index=" + index +
'}';
}
UserInfo userInfo;
int type;
int index;
}
package com.iflytek.request.design.prototype;
import androidx.annotation.NonNull;
public class UserInfo implements Cloneable{
public UserInfo(String name, String phone){
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@NonNull
@Override
protected UserInfo clone() throws CloneNotSupportedException {
return (UserInfo)super.clone();
}
@Override
public String toString() {
return "UserInfo{" +
hashCode() + '\'' +
"name='" + name + '\'' +
", phone='" + phone + '\'' +
'}';
}
String name;
String phone;
}
package com.iflytek.request.design.prototype;
import android.util.Log;
import com.iflytek.request.tool.LogY;
public class Prototype {
public static void test() throws CloneNotSupportedException{
UserInfo userInfo = new UserInfo("Yj","1333333");
People people = new People(userInfo,111111111,222222222);
People clonePeople = people.clone();
LogY.v("people = "+people);
LogY.v("clonePeople = "+clonePeople);
userInfo.setName("yws");
LogY.v("people = "+people);
LogY.v("clonePeople = "+clonePeople);
}
}
package com.iflytek.request.design.flyweight;
import java.util.ArrayList;
import java.util.HashMap;
public class FlyWeight {
public static void testFly() {
new TreeNode(1, 1, FactoryFly.getTree("yj", "11111111111"));
new TreeNode(1, 2, FactoryFly.getTree("yj", "2222222222"));
new TreeNode(2, 1, FactoryFly.getTree("yws", "11111111111"));
new TreeNode(2, 2, FactoryFly.getTree("yws", "222222222"));
}
public static class FactoryFly {
public static HashMap hashMap = new HashMap<>();
public static Tree getTree(String name, String date) {
if (hashMap.containsKey(name)) {
return hashMap.get(name);
}
Tree tree = new Tree(name, date);
hashMap.put(name, tree);
return tree;
}
}
public static class Tree {
private String name;
private String date;
public Tree(String name, String date) {
this.name = name;
this.date = date;
}
public String getName() {
return name;
}
public String getDate() {
return date;
}
}
static class TreeNode {
int x = 0;
int y = 0;
Tree tree;
public TreeNode(int x, int y, Tree tree) {
this.x = x;
this.y = y;
this.tree = tree;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Tree getTree() {
return tree;
}
}
}
package com.iflytek.request.design.adapter.rcl;
public class RecycleView {
Adapter mAdapter;
public void setAdapter(Adapter adapter) {
mAdapter = adapter;
onBindViewHolder();
getItemCount();
}
public void onBindViewHolder() {
mAdapter.bindViewHolder();
}
public void getItemCount() {
mAdapter.getItemCount();
}
public abstract static class Adapter {
public abstract void bindViewHolder();
public abstract int getItemCount();
}
}
package com.iflytek.request.design.adapter.rcl;
import com.iflytek.request.tool.LogY;
public class TestAdapter extends RecycleView.Adapter{
@Override
public void bindViewHolder() {
LogY.v("bindViewHolder");
}
@Override
public int getItemCount() {
LogY.v("getItemCount");
return 0;
}
}
package com.iflytek.request.design.adapter.rcl;
public class Test {
public static void testAdapter(){
RecycleView.Adapter adapter = new TestAdapter();
RecycleView rcy = new RecycleView();
rcy.setAdapter(adapter);
}
}
package com.iflytek.request.design.decorator;
import com.iflytek.request.tool.LogY;
public class TestDecorator {
public void init(){
Component component = new CreateComponent();
component = new Component_A(component);
component = new Component_B(component);
component.operation();
}
public interface Component {
void operation();
}
public class CreateComponent implements Component {
@Override
public void operation() {
LogY.v("主要的功能!!!");
}
}
public class Component_Main implements Component {
Component createComponent = null;
public Component_Main(Component createComponent){
this.createComponent = createComponent;
}
@Override
public void operation() {
createComponent.operation();
}
}
public class Component_A extends Component_Main {
public Component_A(Component createComponent) {
super(createComponent);
}
private void method_A() {
LogY.v("A功能!!!");
}
@Override
public void operation() {
this.method_A();
super.operation();
}
}
public class Component_B extends Component_Main {
public Component_B(Component createComponent) {
super(createComponent);
}
private void method_B() {
LogY.v("B功能!!!");
}
@Override
public void operation() {
this.method_B();
super.operation();
}
}
}
package com.iflytek.request.design.strategy;
import com.iflytek.request.tool.LogY;
public class StrategyTest {
public void init(){
StrategyContext add = new StrategyContext(new AddStrategy());
LogY.v("++++++++++++" + add.executeStrategy(8,2));
StrategyContext subtrack = new StrategyContext(new SubtrackStrategy());
LogY.v("------------" + subtrack.executeStrategy(8,2));
StrategyContext multiply = new StrategyContext(new MultiplyStrategy());
LogY.v("***********" + multiply.executeStrategy(8,2));
}
public class StrategyContext{
Strategy strategy;
public StrategyContext(Strategy strategy ){
this.strategy = strategy;
}
//此类封装策略模式,根据传入参数,分发不同角色
public int executeStrategy(int a, int b){
return strategy.doOperation(a,b);
}
}
public interface Strategy{
int doOperation(int a, int b);
}
public class AddStrategy implements Strategy{
@Override
public int doOperation(int a, int b) {
return a + b;
}
}
public class SubtrackStrategy implements Strategy{
@Override
public int doOperation(int a, int b) {
return a - b;
}
}
public class MultiplyStrategy implements Strategy{
@Override
public int doOperation(int a, int b) {
return a * b;
}
}
}
package com.iflytek.request.design.chain;
import com.iflytek.request.tool.LogY;
public class ChainTest {
public void init(){
Request request = new Request.ReuestBuilder().loggedOn(true).isPermits(true).frequentOK(true).containsSensitiveWords(true).build();
Handler loggedOn = new LoggedOn(new IsPermits(null));
if (loggedOn.process(request)){
LogY.v("正常业务处理");
}else {
LogY.v("访问异常");
}
}
abstract class Handler{
Handler next;
public Handler(Handler next){
this.next = next;
}
public Handler getNext() {
return next;
}
public void setNext(Handler next) {
this.next = next;
}
abstract boolean process(Request request);
}
class LoggedOn extends Handler{
public LoggedOn(Handler next) {
super(next);
}
@Override
boolean process(Request request) {
if (request.isLoggedOn()){
LogY.v("LoggedOn");
Handler handler = getNext();
if (null == handler){
return true;
}
if (handler.process(request)){
return true;
}
}
return false;
}
}
class IsPermits extends Handler{
public IsPermits(Handler next) {
super(next);
}
@Override
boolean process(Request request) {
if (request.isPermits()){
Handler handler = getNext();
LogY.v("IsPermits");
if (null == handler){
return true;
}
if (handler.process(request)){
return true;
}
}
return false;
}
}
}
package com.iflytek.request.design.chain;
class Request {
private boolean loggedOn;
public boolean isLoggedOn() {
return loggedOn;
}
public void setLoggedOn(boolean loggedOn) {
this.loggedOn = loggedOn;
}
public boolean isFrequentOK() {
return frequentOK;
}
public void setFrequentOK(boolean frequentOK) {
this.frequentOK = frequentOK;
}
public boolean isPermits() {
return isPermits;
}
public void setPermits(boolean permits) {
isPermits = permits;
}
public boolean isContainsSensitiveWords() {
return containsSensitiveWords;
}
public void setContainsSensitiveWords(boolean containsSensitiveWords) {
this.containsSensitiveWords = containsSensitiveWords;
}
private boolean frequentOK;
private boolean isPermits;
private boolean containsSensitiveWords;
private String requestBody;
private Request(boolean a, boolean b, boolean c, boolean d) {
this.loggedOn = a;
this.frequentOK = b;
this.isPermits = c;
this.containsSensitiveWords = d;
}
public static class ReuestBuilder {
private boolean loggedOn;
private boolean frequentOK;
private boolean isPermits;
private boolean containsSensitiveWords;
public ReuestBuilder loggedOn(boolean loggedOn) {
this.loggedOn = loggedOn;
return this;
}
public ReuestBuilder frequentOK(boolean frequentOK) {
this.frequentOK = frequentOK;
return this;
}
public ReuestBuilder isPermits(boolean isPermits) {
this.isPermits = isPermits;
return this;
}
public ReuestBuilder containsSensitiveWords(boolean containsSensitiveWords) {
this.containsSensitiveWords = containsSensitiveWords;
return this;
}
public Request build() {
return new Request(loggedOn, frequentOK, isPermits, containsSensitiveWords);
}
}
}