beans.xml 文件中
prototype”/>
编写软件过程中,程序员面临着来自 耦合性、内聚性以及可维护性、可扩展性、重用性、灵活性 等多方面的挑战,设计模式是为了让程序(软件),具有更好的:
设计模式原则,其实就是程序员在编程时,应当遵守的原则,也是各种设计模式的基础(即:设计模式为什么这样设计的依据)
对类来说的,即一个类应该只负责一项职责。如类A负责两个不同职责:职责1、职责2。当职责1需求变更而改变A时,可能造成职责2执行错误,所以需要将类A的粒度分解为A1,A2。
/**
* 单一职责原则
*
* @author yangwei
* @date 2020-06-25 21:42
*/
public class SingleResponsibilityCase {
/**
* 方式一:违反了单一职责原则
* 解决方案:根据交通工具的不同,分解成不同的类
*/
static class VehicleUtil {
static void run(String vehicle) {
System.out.println(vehicle + " 在公路上跑...");
}
}
/**
* 方式二:遵循单一职责原则,即将类分解,同时修改客户端
*/
static class RoadVehicleUtil {
static void run(String vehicle) {
System.out.println(vehicle + " 在公路上跑...");
}
}
static class AirVehicleUtil {
static void run(String vehicle) {
System.out.println(vehicle + " 在天空中飞行...");
}
}
/**
* 方式三:没有对原有的类做大的修改,在类上没有遵循单一职责原则,但是在方法上遵循单一职责原则
*/
static class VehicleUtil2 {
static void run(String vehicle) {
System.out.println(vehicle + " 在公路上跑...");
}
static void runAir(String vehicle) {
System.out.println(vehicle + " 在天空中飞行...");
}
static void runWater(String vehicle) {
System.out.println(vehicle + " 在水中运行...");
}
}
public static void main(String[] args) {
System.out.println("方式一:");
VehicleUtil.run("汽车");
VehicleUtil.run("摩托车");
VehicleUtil.run("飞机");
System.out.println("方式二:");
RoadVehicleUtil.run("汽车");
RoadVehicleUtil.run("摩托车");
AirVehicleUtil.run("飞机");
System.out.println("方式三:");
VehicleUtil2.run("汽车");
VehicleUtil2.runWater("轮船");
VehicleUtil2.runAir("飞机");
}
}
public class InterfaceSegregationCase {
interface Interface1 {
void operation1();
}
interface Interface2 {
void operation2();
void operation3();
}
interface Interface3 {
void operation4();
void operation5();
}
static class B implements Interface1, Interface2 {
public void operation1() {
System.out.println("B 实现了 operation1");
}
public void operation2() {
System.out.println("B 实现了 operation2");
}
public void operation3() {
System.out.println("B 实现了 operation3");
}
}
static class D implements Interface1, Interface3 {
public void operation1() {
System.out.println("D 实现了 operation1");
}
public void operation4() {
System.out.println("D 实现了 operation4");
}
public void operation5() {
System.out.println("D 实现了 operation5");
}
}
static class A {
void depend1(Interface1 i) {
i.operation1();
}
void depend2(Interface2 i) {
i.operation2();
}
void depend3(Interface2 i) {
i.operation3();
}
}
static class C {
void depend1(Interface1 i) {
i.operation1();
}
void depend4(Interface3 i) {
i.operation4();
}
void depend5(Interface3 i) {
i.operation5();
}
}
public static void main(String[] args) {
A a = new A();
// A 类通过接口去依赖 B 类
a.depend1(new B());
a.depend2(new B());
a.depend3(new B());
C c = new C();
// C 类通过接口去依赖 D 类
c.depend1(new D());
c.depend4(new D());
c.depend5(new D());
}
}
public class DependenceInversionCase {
//region -- 方式一
// /**
// * 方式一
// * 优点:简单
// * 缺点:如果我们通过 微信、短信 等获取,则需要新增类,同时Person类也需要增加相应的接收方法
// */
// static class Email {
// String getInfo() {
// return "电子邮件信息:Hello World";
// }
// }
// static class Person {
// void receive(Email email) {
// System.out.println(email.getInfo());
// }
// }
//endregion
//region
/**
* 方式二
* 引入一个抽象的接口 IReceiver, 表示接收者, 这样 Person 类与接口 IReceiver 发生依赖
* 因为 Email, WeiXin 等等属于接收的范围,他们各自实现 IReceiver 接口就可以了,这样我们就符号依赖倒转原则
*/
interface IReceiver {
String getInfo();
}
static class Email implements IReceiver {
public String getInfo() {
return "电子邮件信息:Hello World";
}
}
static class WeChat implements IReceiver {
public String getInfo() {
return "微信信息:来红包啦!";
}
}
static class Person {
// 这里是对接口的依赖
void receive(IReceiver receiver) {
System.out.println(receiver.getInfo());
}
}
//endregion
public static void main(String[] args) {
Person person = new Person();
person.receive(new Email());
person.receive(new WeChat());
}
}
public class DependencyPass {
public static void main(String[] args) {
// // 通过接口传递实现依赖
// OpenAndClose openAndClose = new OpenAndClose();
// openAndClose.open(new ChangHong());
// // 通过构造器进行依赖传递
// OpenAndClose2 openAndClose = new OpenAndClose2(new ChangHong());
// openAndClose.open();
// 通过 setter 方法进行依赖传递
OpenAndClose3 openAndClose = new OpenAndClose3();
openAndClose.setTv(new ChangHong());
openAndClose.open();
}
}
/**
* 电视接口
*/
interface ITV {
void play();
}
/**
* 开关接口
*/
interface IOpenAndClose {
void open(ITV tv);
}
/**
* 方式 1: 通过接口传递实现依赖
*/
class ChangHong implements ITV {
public void play() {
System.out.println("长虹电视机,打开");
}
}
class OpenAndClose implements IOpenAndClose {
public void open(ITV tv) {
tv.play();
}
}
/**
* 方式 2: 通过构造方法依赖传递
*/
interface IOpenAndClose2 {
void open();
}
class OpenAndClose2 implements IOpenAndClose2 {
private ITV tv;
public OpenAndClose2(ITV tv) {
this.tv = tv;
}
public void open() {
this.tv.play();
}
}
/**
* 方式 3: 通过 setter 方法传递
*/
interface IOpenAndClose3 {
void open();
void setTv(ITV tv);
}
class OpenAndClose3 implements IOpenAndClose3 {
private ITV tv;
public void open() {
this.tv.play();
}
public void setTv(ITV tv) {
this.tv = tv;
}
}
public class LiskovSubstitutionCase {
public static void main(String[] args) {
A a = new A();
System.out.println("11-3=" + a.func1(11, 3));
System.out.println("1-8=" + a.func1(1, 8));
System.out.println("-----------------------");
B b = new B();
System.out.println("11-3=" + b.func1(11, 3));
System.out.println("1-8=" + b.func1(1, 8));
System.out.println("11+3+9=" + b.func2(11, 3));
}
}
class A {
public int func1(int num1, int num2) { return num1 - num2; }
}
class B extends A {
@Override
public int func1(int a, int b) { return a + b; }
public int func2(int a, int b) { return func1(a, b) + 9; }
}
//结果输出
//11-3=8
//1-8=-7
//-----------------------
//11-3=14
//1-8=9
//11+3+9=23
class Base {}
class A extends Base {
public int func1(int num1, int num2) { return num1 - num2; }
}
class B extends Base {
// 如果B需要使用A类的方法,使用组合关系
private A a = new A();
public int func1(int a, int b) { return a + b; }
public int func2(int a, int b) { return func1(a, b) + 9; }
public int func3(int a, int b) { return this.a.func1(a, b); }
}
public class LiskovSubstitutionCase {
public static void main(String[] args) {
B b = new B();
// System.out.println("11-3=" + b.func1(11, 3));
// System.out.println("1-8=" + b.func1(1, 8));
// System.out.println("11+3+9=" + b.func2(11, 3));
// 因为B不在集成A类,因此调用者不会再用func1来求减法,而是用func3
System.out.println("11-3=" + b.func3(11, 3));
System.out.println("1-8=" + b.func3(1, 8));
System.out.println("11+3+9=" + b.func2(11, 3));
}
}
public class OpenClosedCase {
public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
graphicEditor.drawShape(new Triangle());
}
}
class GraphicEditor {
public void drawShape(Shape s) {
if (s.type == 1) {
drawRectangle(s);
} else if (s.type == 2) {
drawCircle(s);
} else if (s.type == 3) {
// 这里需要改动
drawTriangle(s);
}
}
private void drawRectangle(Shape r) {
System.out.println("绘制矩形");
}
private void drawCircle(Shape r) {
System.out.println("绘制圆形");
}
/**
* 这里也需要新增方法
*/
private void drawTriangle(Shape r) {
System.out.println("绘制三角形");
}
}
class Shape {
int type;
}
class Rectangle extends Shape {
Rectangle() {
super.type = 1;
}
}
class Circle extends Shape {
Circle() {
super.type = 2;
}
}
/**
* 新增画三角形
*/
class Triangle extends Shape {
Triangle() {
super.type = 3;
}
}
public class OpenClosedCase {
public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
graphicEditor.drawShape(new Triangle());
}
}
/**
* 改进方案:
*/
abstract class Shape {
int type;
abstract void draw();
}
class Rectangle extends Shape {
Rectangle() {
super.type = 1;
}
@Override
public void draw() {
System.out.println("绘制矩形");
}
}
class Circle extends Shape {
Circle() {
super.type = 2;
}
@Override
public void draw() {
System.out.println("绘制圆形");
}
}
class Triangle extends Shape {
Triangle() {
super.type = 3;
}
@Override
public void draw() {
System.out.println("绘制三角形");
}
}
class GraphicEditor {
public void drawShape(Shape s) {
s.draw();
}
}
public class DemeterCase {
public static void main(String[] args) {
SchoolManager schoolManager = new SchoolManager();
schoolManager.printAllEmployee(new CollegeManager());
}
}
/**
* 学校总部员工
*/
class Employee {
private String id;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
/**
* 学校学院员工
*/
class CollegeEmployee {
private String id;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
/**
* 管理学校学院员工的类
*/
class CollegeManager {
public List<CollegeEmployee> getAllEmployee() {
List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
for (int i = 0; i < 10; i++) {
CollegeEmployee emp = new CollegeEmployee();
emp.setId("学校学院员工 id= " + i);
list.add(emp);
}
return list;
}
}
/**
* 管理学校总部员工的类
* 分析:SchoolManager 类的直接朋友有哪些【Employee、CollegeManager】
* 但是 CollegeEmployee 类并不是 SchoolManager 类的直接朋友,这样就违背了迪米特法则
*/
class SchoolManager {
public List<Employee> getAllEmployee() {
List<Employee> list = new ArrayList<Employee>();
for (int i = 0; i < 5; i++) {
Employee emp = new Employee();
emp.setId("学校总部员工 id= " + i);
list.add(emp);
}
return list;
}
void printAllEmployee(CollegeManager sub) {
List<CollegeEmployee> list1 = sub.getAllEmployee();
System.out.println("------------学校学院员工------------");
for (CollegeEmployee e : list1) {
System.out.println(e.getId());
}
List<Employee> list2 = this.getAllEmployee();
System.out.println("------------学校总部员工------------");
for (Employee e : list2) {
System.out.println(e.getId());
}
}
}
画UML图与写文章差不多,都是把自己的思想描述给别人看,关键在于思路和条理,UML图分类:
public class Person{ //代码形式->类图 private Integer id;
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
public class PersonServiceBean {
private PersonDao personDao;//类
public void save(Person person){}
public IDCard getIDCard(Integer personid){}
public void modify(){
Department department = new Department();
}
}
public class PersonDao{}
public class IDCard{}
public class Person{}
public class Department{}
* 类中用到了对方
* 如果是类的成员属性
* 如果是方法的返回类型
* 是方法接收的参数类型
* 方法中使用到
设计模式分为三种类型,共23种。
public class SingletonCase01 {
public static void main(String[] args) {
Singleton1 instance1 = Singleton1.getInstance();
Singleton1 instance2 = Singleton1.getInstance();
System.out.println(instance1 == instance2);
}
}
class Singleton1 {
/**
* 1、构造器私有化(防止 new)
*/
private Singleton1(){}
/**
* 2、类的内部创建对象
*/
private static final Singleton1 INSTANCE = new Singleton1();
/**
* 3、向外暴露一个静态的公共方法
*/
public static Singleton1 getInstance() {
return INSTANCE;
}
}
public class SingletonCase02 {
public static void main(String[] args) {
Singleton2 instance1 = Singleton2.getInstance();
Singleton2 instance2 = Singleton2.getInstance();
System.out.println(instance1 == instance2);
}
}
class Singleton2 {
/**
* 1、构造器私有化(防止 new)
*/
private Singleton2(){}
/**
* 2、类的内部创建对象:在静态代码块执行时,创建单例对象
*/
private static Singleton2 INSTANCE;
static {
INSTANCE = new Singleton2();
}
/**
* 3、向外暴露一个静态的公共方法
*/
public static Singleton2 getInstance() {
return INSTANCE;
}
}
public class SingletonCase03 {
public static void main(String[] args) {
// Singleton3 instance1 = Singleton3.getInstance();
// Singleton3 instance2 = Singleton3.getInstance();
// System.out.println(instance1 == instance2);
for (int i = 0; i < 50; i++) {
new Thread(() -> System.out.println(Singleton3.getInstance().hashCode())).start();
}
}
}
class Singleton3 {
private Singleton3(){}
private static Singleton3 INSTANCE;
/**
* 提供一个静态的公有方法,当使用到该方法时,才去创建 instance
*/
public static Singleton3 getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton3();
}
return INSTANCE;
}
}
public class SingletonCase04 {
public static void main(String[] args) {
for (int i = 0; i < 50; i++) {
new Thread(() -> System.out.println(Singleton4.getInstance().hashCode())).start();
}
}
}
class Singleton4 {
private Singleton4(){}
private static Singleton4 INSTANCE;
/**
* 加synchronized,解决多线程不安全问题
*/
public static synchronized Singleton4 getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton4();
}
return INSTANCE;
}
}
public class SingletonCase05 {
public static void main(String[] args) {
for (int i = 0; i < 50; i++) {
new Thread(() -> System.out.println(Singleton5.getInstance().hashCode())).start();
}
}
}
class Singleton5 {
private Singleton5(){}
private static Singleton5 INSTANCE;
/**
* 加synchronized,解决多线程不安全问题
*/
public static Singleton5 getInstance() {
if (INSTANCE == null) {
synchronized (Singleton5.class) {
INSTANCE = new Singleton5();
}
}
return INSTANCE;
}
}
public class SingletonCase06 {
public static void main(String[] args) {
for (int i = 0; i < 50; i++) {
new Thread(() -> System.out.println(Singleton6.getInstance().hashCode())).start();
}
}
}
class Singleton6 {
private Singleton6(){}
/**
* 这里的 volatile 一定不能够少,防止获取到半初始化状态的实例
*/
private static volatile Singleton6 INSTANCE;
/**
* 加synchronized,解决多线程不安全问题
*/
public static Singleton6 getInstance() {
if (INSTANCE == null) {
synchronized (Singleton6.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton6();
}
}
}
return INSTANCE;
}
}
public class SingletonCase07 {
public static void main(String[] args) {
for (int i = 0; i < 50; i++) {
new Thread(() -> System.out.println(Singleton7.getInstance().hashCode())).start();
}
}
}
class Singleton7 {
private Singleton7() {}
/**
* 使用静态内部类,在Singleton7被加载时,不会被加载
* 只有在getInstance()时被加载,并且加载时是线程安全的
*/
private static class SingletonInstance {
private static final Singleton7 INSTANCE = new Singleton7();
}
public static Singleton7 getInstance() {
return SingletonInstance.INSTANCE;
}
}
public class SingletonCase08 {
public static void main(String[] args) {
for (int i = 0; i < 50; i++) {
new Thread(() -> System.out.println(Singleton8.getInstance().hashCode())).start();
}
}
}
class Singleton8 {
private Singleton8() {}
static enum SingletonInstance {
INSTANCE;
private Singleton8 singleton8;
// 私有化枚举的构造函数
private SingletonInstance() {
singleton8 = new Singleton8();
}
public Singleton8 getInstance() {
return singleton8;
}
}
public static Singleton8 getInstance() {
return SingletonInstance.INSTANCE.getInstance();
}
}
/**
* 定义一个披萨的抽象类
*/
public abstract class Pizza {
/**
* 披萨名字
*/
protected String name;
/**
* 原材料准备
*/
public abstract void prepare();
public void bake(){
System.out.println(name + " baking;");
}
public void cut() {
System.out.println(name + " cutting;");
}
public void box() {
System.out.println(name + " boxing;");
}
public Pizza(String name) {
this.name = name;
}
}
// 奶酪披萨
public class CheesePizza extends Pizza {
public CheesePizza() {
super("奶酪披萨");
}
@Override
public void prepare() {
System.out.println("给制作奶酪披萨准备原材料");
}
}
// 希腊披萨
public class GreekPizza extends Pizza {
public GreekPizza() {
super("希腊披萨");
}
@Override
public void prepare() {
System.out.println("给希腊披萨准备原材料");
}
}
/**
* 披萨订购
*/
public class PizzaOrder {
Pizza pizza = null;
public PizzaOrder() {
String orderType = "";
do {
orderType = getType();
if (orderType.equals("greek")) {
pizza = new GreekPizza();
} else if (orderType.equals("cheese")) {
pizza = new CheesePizza();
} else {
break;
}
// 输出披萨制作过程
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
} while (true);
}
/**
* 获取客户希望订购披萨的种类
*/
private String getType() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("input pizza type: ");
return in.readLine();
} catch (IOException e) {
System.out.println(e.getMessage());
return "";
}
}
}
// 披萨店
public class PizzaStore {
public static void main(String[] args) {
new PizzaOrder();
}
}
public class SimpleFactory {
public Pizza createPizza(String orderType) {
Pizza pizza = null;
if (orderType.equals("greek")) {
pizza = new GreekPizza();
} else if (orderType.equals("cheese")) {
pizza = new CheesePizza();
}
if (pizza != null) {
// 输出披萨制作过程
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
}
return pizza;
}
}
public class PizzaOrder {
SimpleFactory simpleFactory;
public PizzaOrder(SimpleFactory simpleFactory) {
do {
this.simpleFactory = simpleFactory;
simpleFactory.createPizza(getType());
} while (true);
}
/**
* 获取客户希望订购披萨的种类
*/
private String getType() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("input pizza type: ");
return in.readLine();
} catch (IOException e) {
System.out.println(e.getMessage());
return "";
}
}
}
public class PizzaStore {
public static void main(String[] args) {
new PizzaOrder(new SimpleFactory());
}
}
public abstract class PizzaOrder {
public PizzaOrderFactory(String desc) {
System.out.println(desc);
do {
Pizza pizza = createPizza(getType());
if (pizza != null) {
// 输出披萨制作过程
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
} else {
System.out.println("没有这种披萨,订购失败");
break;
}
} while (true);
}
/**
* 交给工厂子类完成
*/
abstract Pizza createPizza(String orderType);
/**
* 获取客户希望订购披萨的种类
*/
private String getType() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("input pizza type: ");
return in.readLine();
} catch (IOException e) {
System.out.println(e.getMessage());
return "";
}
}
}
public class BJPizzaOrderFactory extends PizzaOrderFactory {
BJPizzaOrderFactory() {
super("开始订购北京披萨");
}
@Override
Pizza createPizza(String orderType) {
if (orderType.equals("cheese")) {
return new BJCheesePizza();
} else if (orderType.equals("pepper")) {
return new BJPepperPizza();
}
return null;
}
}
public class LDPizzaOrderFactory extends PizzaOrderFactory {
LDPizzaOrderFactory() {
super("开始订购伦敦披萨");
}
@Override
Pizza createPizza(String orderType) {
if (orderType.equals("cheese")) {
return new LDCheesePizza();
} else if (orderType.equals("pepper")) {
return new LDPepperPizza();
}
return null;
}
}
public abstract class AbstractPizzaOrderFactory {
AbstractPizzaOrderFactory(String desc) {
System.out.println(desc);
}
abstract Pizza createPizza(String orderType);
}
public class BJPizzaOrderFactory extends AbstractPizzaOrderFactory {
BJPizzaOrderFactory() {
super("开始订购北京披萨");
}
@Override
Pizza createPizza(String orderType) {
if (orderType.equals("cheese")) {
return new BJCheesePizza();
} else if (orderType.equals("pepper")) {
return new BJPepperPizza();
}
return null;
}
}
public class LDPizzaOrderFactory extends AbstractPizzaOrderFactory {
LDPizzaOrderFactory() {
super("开始订购伦敦披萨");
}
@Override
Pizza createPizza(String orderType) {
if (orderType.equals("cheese")) {
return new LDCheesePizza();
} else if (orderType.equals("pepper")) {
return new LDPepperPizza();
}
return null;
}
}
public class JDKFactory {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
}
}
↓↓↓↓↓
public static Calendar getInstance()
{
return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
}
↓↓↓↓↓
private static Calendar createCalendar(TimeZone zone, Locale aLocale)
{
CalendarProvider provider =
LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale)
.getCalendarProvider();
if (provider != null) {
try {
return provider.getInstance(zone, aLocale);
} catch (IllegalArgumentException iae) {
// fall back to the default instantiation
}
}
Calendar cal = null;
// 下面就是工厂模式
if (aLocale.hasExtensions()) {
String caltype = aLocale.getUnicodeLocaleType("ca");
if (caltype != null) {
switch (caltype) {
case "buddhist":
cal = new BuddhistCalendar(zone, aLocale);
break;
case "japanese":
cal = new JapaneseImperialCalendar(zone, aLocale);
break;
case "gregory":
cal = new GregorianCalendar(zone, aLocale);
break;
}
}
}
if (cal == null) {
if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {
cal = new BuddhistCalendar(zone, aLocale);
} else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"
&& aLocale.getCountry() == "JP") {
cal = new JapaneseImperialCalendar(zone, aLocale);
} else {
cal = new GregorianCalendar(zone, aLocale);
}
}
return cal;
}
public class SheepCase {
public static void main(String[] args) {
// 传统方法
Sheep sheep = new Sheep("Tom", 1, "白色");
Sheep sheep2 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
Sheep sheep3 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
Sheep sheep4 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
Sheep sheep5 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
// ...
System.out.println(sheep);
System.out.println(sheep2);
System.out.println(sheep3);
System.out.println(sheep4);
System.out.println(sheep5);
}
}
class Sheep {
private String name;
private int age;
private String color;
Sheep(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
// setter、getter
}
class Sheep implements Cloneable {
private String name;
private int age;
private String color;
Sheep(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
// setter、getter
@Override
public String toString() {
return "Sheep: {name: " + name + ", age: " + age + ", color: " + color + "}";
}
@Override
protected Object clone() {
try {
Sheep sheep = (Sheep) super.clone();
return super.clone();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
public Sheep getCopy() {
return (Sheep) clone();
}
}
/**
* 深浅复制
*/
public class DeepShallowCopy implements Cloneable, Serializable {
private static final long serialVersionUID = 1L;
private String string;
private SerializableObject obj;
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public SerializableObject getObj() {
return obj;
}
public void setObj(SerializableObject obj) {
this.obj = obj;
}
/**
* 浅复制
*/
public Object shallowClone() throws CloneNotSupportedException{
DeepShallowCopy proto = (DeepShallowCopy) super.clone();
return proto;
}
/**
* 深复制
* @throws ClassNotFoundException
*/
public Object deepClone() throws IOException, ClassNotFoundException{
// 写入当前对象的二进制流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
// 读出二进制流产生的新对象
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
}
}
class SerializableObject implements Serializable{
private static final long serialVersionUID = 1L;
}
public abstract class AbstractHouse {
abstract void buildBasic();
abstract void buildWalls();
abstract void roofed();
public void build() {
buildBasic();
buildWalls();
roofed();
System.out.println("房子建造完成~~");
}
}
public class CommonHouse extends AbstractHouse {
@Override
void buildBasic() {
System.out.println("普通房子 打地基");
}
@Override
void buildWalls() {
System.out.println("普通房子 砌墙");
}
@Override
void roofed() {
System.out.println("普通房子 盖屋顶");
}
}
public class BuildHouseCase {
public static void main(String[] args) {
CommonHouse commonHouse = new CommonHouse();
commonHouse.build();
}
}
// 产品
public class House {
private String basic;
private String wall;
private String roofed;
// setter、getter
@Override
public String toString() {
return "House: {basic: " + basic + ", wall: " + wall + ", roofed: " + roofed + "}";
}
}
// 房子构建抽象类
public abstract class HouseBuilder {
protected House house = new House();
abstract void buildBasic();
abstract void buildWalls();
abstract void roofed();
public House getHouse() {
return house;
}
}
// 房子的具体构建者-普通房子
public class CommonHouse extends HouseBuilder {
@Override
void buildBasic() {
System.out.println("普通房子 打地基 5 米");
house.setBasic("5 米");
}
@Override
void buildWalls() {
System.out.println("普通房子 砌墙 10 厘米");
house.setWall("10 厘米");
}
@Override
void roofed() {
System.out.println("普通房子屋顶");
house.setRoofed("普通屋顶");
}
}
// 房子的具体构建者-高楼
public class HighBuildingHouse extends HouseBuilder {
@Override
void buildBasic() {
System.out.println("高楼 打地基 100 米");
house.setBasic("100 米");
}
@Override
void buildWalls() {
System.out.println("高楼 砌墙 25 厘米");
house.setWall("25 厘米");
}
@Override
void roofed() {
System.out.println("高楼屋顶");
house.setRoofed("高楼屋顶");
}
}
// 指挥者:去指定建造房子的流程
public class HouseDirector {
private HouseBuilder builder;
HouseDirector(HouseBuilder builder) {
this.builder = builder;
}
public House build() {
builder.buildBasic();
builder.buildWalls();
builder.roofed();
return builder.getHouse();
}
}
public class BuildHouseCase {
public static void main(String[] args) {
CommonHouse commonHouse = new CommonHouse();
HouseDirector director = new HouseDirector(commonHouse);
House house1 = director.build();
System.out.println(house1);
HighBuildingHouse highBuildingHouse = new HighBuildingHouse();
director = new HouseDirector(highBuildingHouse);
House house2 = director.build();
System.out.println(house2);
}
}
public class JDKBuilder {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Hello, World");
System.out.println(sb);
}
}
↓↓↓↓↓
// public final class StringBuilder extends AbstractStringBuilder implements java.io.Serializable, CharSequence
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
↓↓↓↓↓
// abstract class AbstractStringBuilder implements Appendable, CharSequence
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}