├── .gitbook └── assets │ ├── 1648900517(1).png │ ├── 1648910128(1).png │ ├── 1648910902.png │ ├── 1648911234(1).png │ ├── 1648911669(1).png │ ├── 1649214342(1).png │ ├── 1649214424(1).png │ ├── 764_b12_512.png │ ├── abstractfactoryfactory.png │ ├── abstractfactoryfactoryclass.png │ ├── abstractfactoryiphone.png │ ├── abstractfactoryiphoneclass.png │ ├── abstractfactoryissue.png │ ├── abstractfactoryrouter.png │ ├── abstractfactoryrouterclass.png │ ├── abstractfactorytest.png │ ├── abstractfactoryuml.png │ ├── factoryfactory.png │ ├── factoryfactoryclass.png │ ├── factorypizza.png │ ├── factorypizzaclass.png │ ├── factorytest.png │ ├── factoryuml.png │ ├── greekpizza.png │ ├── image (1).png │ ├── image.png │ ├── observerTest.png │ ├── observercat.png │ ├── observerdog.png │ ├── observerissue.png │ ├── observermouse.png │ ├── observerobserver.png │ ├── observerobservered.png │ ├── observertestit.png │ ├── productbuffer1.png │ ├── productbuffer2.png │ ├── productcomsumer.png │ ├── productissue.png │ ├── productproducer.png │ ├── producttest.png │ ├── productuml.png │ ├── simplefactorypizza.png │ ├── simplefactorypizzafactory.png │ ├── simplefactoryuml.png │ ├── singlehungry.png │ ├── singlehungryandlock.png │ ├── singleissue.png │ ├── singlelazy.png │ ├── singleuml.png │ ├── templateredmilk.png │ ├── templatesoymilk.png │ ├── templatetest.png │ └── templateuml.png ├── 10种设计模式 ├── README.md ├── 单例模式.md ├── 工厂模式.md ├── 抽象工厂模式.md ├── 数据访问对象模式.md ├── 模板模式.md ├── 生产者消费者模式.md ├── 策略模式.md ├── 简单工厂模式.md ├── 观察者模式.md └── 迭代器模式.md ├── README.md ├── src ├── InputTest.java ├── Main.java ├── MyException.java ├── Person.java ├── Sort.java ├── Type.java └── Welcome.java ├── src10 ├── prodconsumer │ ├── .idea │ │ ├── .gitignore │ │ ├── misc.xml │ │ └── modules.xml │ ├── Buffer.java │ ├── Consumer.java │ ├── Main.java │ └── Producer.java └── thread │ ├── AddDec.java │ ├── DeadLock.java │ ├── DeadLockExample2.java │ ├── FutureDemo.java │ ├── FutureTaskDemo.java │ ├── InterruptTest.java │ ├── RunnableVSThread.java │ ├── SetDaemonDemo.java │ └── ThreadPoolDemo.java ├── src11 ├── Generic │ ├── Durian.java │ ├── GenericDurian.java │ ├── GenericMethod.java │ ├── GenericTest.java │ ├── GeneticStaticMethod.java │ ├── ShowInterface.java │ ├── ShowInterfaceTest.java │ └── WildCardDemo.java ├── Reflect │ ├── ConTest.java │ ├── FieldTest.java │ ├── MethodTest.java │ ├── Singleton.java │ ├── SingletonTest.java │ ├── Student.java │ ├── Test.java │ ├── forNameTest.java │ └── getClassTest.java └── TemplateMethod │ ├── Client.java │ ├── PureSoyMilk.java │ ├── RedBeanSoyMilk.java │ └── SoyMilk.java ├── src12 ├── SocketTest │ ├── Client.java │ ├── Send.java │ └── Server.java ├── observerTest │ ├── Cat.java │ ├── Client.java │ ├── Dog.java │ ├── Mouse.java │ ├── MyObserver.java │ └── MySubject.java └── urlTest │ ├── URLDemo.java │ └── UrlSite.java ├── src3 ├── ArrayTest.java └── Person.java ├── src4 ├── abstract │ ├── Main.java │ ├── Person.java │ ├── Student.java │ └── Teacher.java ├── exception │ ├── Main.java │ ├── MyException.java │ └── exception_eg.java ├── inhent │ ├── Person.java │ ├── PolymorphismTest.java │ ├── Student.java │ └── Teacher.java ├── innerClass │ ├── Father.java │ ├── Main.java │ ├── Mother.java │ └── Son.java ├── innerClassByInterface │ ├── Daughter.java │ ├── Father.java │ ├── Girl.java │ └── Mother.java ├── interface │ ├── Main.java │ ├── Person.java │ ├── Student.java │ └── Teacher.java ├── object │ ├── Student.java │ └── TestObject.java └── super │ ├── Main.java │ ├── Person.java │ └── Student.java ├── src5 ├── abstractFactory │ ├── HuaweiFactory.java │ ├── HuaweiPhone.java │ ├── HuaweiRouter.java │ ├── IPhoneProduct.java │ ├── IProductFactory.java │ ├── IRouterProduct.java │ ├── TestFactoryMain.java │ ├── XiaomiFactory.java │ ├── XiaomiPhone.java │ └── XiaomiRounter.java ├── factory │ ├── CheesePizza.java │ ├── ChicagoPizzaStore.java │ ├── GreekPizza.java │ ├── NYPizzaStore.java │ ├── PepperoniPizza.java │ ├── Pizza.java │ ├── PizzaStore.java │ ├── TestOrderPizza.java │ └── VeggiePizza.java ├── simplefactory │ ├── CheesePizza.java │ ├── GreekPizza.java │ ├── PepperoniPizza.java │ ├── Pizza.java │ ├── PizzaStore.java │ └── SimplePizzaFactory.java └── singleton │ └── SingletonPattern.java ├── src6 ├── example │ ├── ATM.java │ ├── BlackBox.java │ └── WhiteBox.java └── test │ ├── BlackBoxTest.java │ └── WhiteBoxTest.java ├── src7 ├── collection │ ├── ArraylistTest.java │ ├── HashmapTest.java │ ├── HashsetTest.java │ └── LinkedlistTest.java ├── iteratorTest │ ├── Aggregate.java │ ├── ConcreteAggregate.java │ ├── ConcreteIterator.java │ ├── Iterator.java │ └── IteratorTest.java └── strategy │ ├── AdvancedMemberStrategy.java │ ├── Client.java │ ├── IntermediateMemberStrategy.java │ ├── MemberStrategy.java │ ├── Price.java │ └── PrimaryMemberStrategy.java ├── src8 ├── DAO │ ├── DataAccessObjectPatternDemo.java │ ├── Student.java │ ├── StudentDAO.java │ └── StudentDaoImpl.java └── fileRW │ ├── BRRead.java │ ├── BRReadLines.java │ ├── ChartoByte.java │ ├── Person.java │ ├── SeriDemo.java │ ├── example_files.java │ └── fileStreamTest.java └── src9 ├── mvc ├── MVCPatternDemo.java ├── Student.java ├── StudentController.java └── StudentView.java └── swingTest ├── BorderLayoutDemo.java ├── ButtonFrame.java ├── ButtonFrame2.java ├── ButtonFrame2Test.java ├── ButtonFrameTest.java ├── SimpleFrame.java ├── SimpleFrameTest.java ├── TestController.java ├── TestModel.java └── TestView.java /.gitbook/assets/1648900517(1).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/1648900517(1).png -------------------------------------------------------------------------------- /.gitbook/assets/1648910128(1).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/1648910128(1).png -------------------------------------------------------------------------------- /.gitbook/assets/1648910902.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/1648910902.png -------------------------------------------------------------------------------- /.gitbook/assets/1648911234(1).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/1648911234(1).png -------------------------------------------------------------------------------- /.gitbook/assets/1648911669(1).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/1648911669(1).png -------------------------------------------------------------------------------- /.gitbook/assets/1649214342(1).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/1649214342(1).png -------------------------------------------------------------------------------- /.gitbook/assets/1649214424(1).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/1649214424(1).png -------------------------------------------------------------------------------- /.gitbook/assets/764_b12_512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/764_b12_512.png -------------------------------------------------------------------------------- /.gitbook/assets/abstractfactoryfactory.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/abstractfactoryfactory.png -------------------------------------------------------------------------------- /.gitbook/assets/abstractfactoryfactoryclass.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/abstractfactoryfactoryclass.png -------------------------------------------------------------------------------- /.gitbook/assets/abstractfactoryiphone.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/abstractfactoryiphone.png -------------------------------------------------------------------------------- /.gitbook/assets/abstractfactoryiphoneclass.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/abstractfactoryiphoneclass.png -------------------------------------------------------------------------------- /.gitbook/assets/abstractfactoryissue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/abstractfactoryissue.png -------------------------------------------------------------------------------- /.gitbook/assets/abstractfactoryrouter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/abstractfactoryrouter.png -------------------------------------------------------------------------------- /.gitbook/assets/abstractfactoryrouterclass.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/abstractfactoryrouterclass.png -------------------------------------------------------------------------------- /.gitbook/assets/abstractfactorytest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/abstractfactorytest.png -------------------------------------------------------------------------------- /.gitbook/assets/abstractfactoryuml.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/abstractfactoryuml.png -------------------------------------------------------------------------------- /.gitbook/assets/factoryfactory.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/factoryfactory.png -------------------------------------------------------------------------------- /.gitbook/assets/factoryfactoryclass.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/factoryfactoryclass.png -------------------------------------------------------------------------------- /.gitbook/assets/factorypizza.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/factorypizza.png -------------------------------------------------------------------------------- /.gitbook/assets/factorypizzaclass.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/factorypizzaclass.png -------------------------------------------------------------------------------- /.gitbook/assets/factorytest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/factorytest.png -------------------------------------------------------------------------------- /.gitbook/assets/factoryuml.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/factoryuml.png -------------------------------------------------------------------------------- /.gitbook/assets/greekpizza.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/greekpizza.png -------------------------------------------------------------------------------- /.gitbook/assets/image (1).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/image (1).png -------------------------------------------------------------------------------- /.gitbook/assets/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/image.png -------------------------------------------------------------------------------- /.gitbook/assets/observerTest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/observerTest.png -------------------------------------------------------------------------------- /.gitbook/assets/observercat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/observercat.png -------------------------------------------------------------------------------- /.gitbook/assets/observerdog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/observerdog.png -------------------------------------------------------------------------------- /.gitbook/assets/observerissue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/observerissue.png -------------------------------------------------------------------------------- /.gitbook/assets/observermouse.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/observermouse.png -------------------------------------------------------------------------------- /.gitbook/assets/observerobserver.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/observerobserver.png -------------------------------------------------------------------------------- /.gitbook/assets/observerobservered.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/observerobservered.png -------------------------------------------------------------------------------- /.gitbook/assets/observertestit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/observertestit.png -------------------------------------------------------------------------------- /.gitbook/assets/productbuffer1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/productbuffer1.png -------------------------------------------------------------------------------- /.gitbook/assets/productbuffer2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/productbuffer2.png -------------------------------------------------------------------------------- /.gitbook/assets/productcomsumer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/productcomsumer.png -------------------------------------------------------------------------------- /.gitbook/assets/productissue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/productissue.png -------------------------------------------------------------------------------- /.gitbook/assets/productproducer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/productproducer.png -------------------------------------------------------------------------------- /.gitbook/assets/producttest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/producttest.png -------------------------------------------------------------------------------- /.gitbook/assets/productuml.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/productuml.png -------------------------------------------------------------------------------- /.gitbook/assets/simplefactorypizza.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/simplefactorypizza.png -------------------------------------------------------------------------------- /.gitbook/assets/simplefactorypizzafactory.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/simplefactorypizzafactory.png -------------------------------------------------------------------------------- /.gitbook/assets/simplefactoryuml.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/simplefactoryuml.png -------------------------------------------------------------------------------- /.gitbook/assets/singlehungry.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/singlehungry.png -------------------------------------------------------------------------------- /.gitbook/assets/singlehungryandlock.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/singlehungryandlock.png -------------------------------------------------------------------------------- /.gitbook/assets/singleissue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/singleissue.png -------------------------------------------------------------------------------- /.gitbook/assets/singlelazy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/singlelazy.png -------------------------------------------------------------------------------- /.gitbook/assets/singleuml.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/singleuml.png -------------------------------------------------------------------------------- /.gitbook/assets/templateredmilk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/templateredmilk.png -------------------------------------------------------------------------------- /.gitbook/assets/templatesoymilk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/templatesoymilk.png -------------------------------------------------------------------------------- /.gitbook/assets/templatetest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/templatetest.png -------------------------------------------------------------------------------- /.gitbook/assets/templateuml.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cuiyungao/JavaCodeExamples/082cf74ece54d3c378debd542a0ef8a53901cf3c/.gitbook/assets/templateuml.png -------------------------------------------------------------------------------- /10种设计模式/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 10种设计模式 3 | --- 4 | 5 | # 10种设计模式 6 | 7 | 课程中共涉及10种设计模式,其中7种来自GOF23,其它3种分别是数据访问对象模式、MVC模式、生产者消费者模式。如图1所示,表格中红色字体是会涉及的GOF设计模式。 8 | 9 | ![图1. 设计模式的分类](../.gitbook/assets/1648900517(1).png) 10 | -------------------------------------------------------------------------------- /10种设计模式/单例模式.md: -------------------------------------------------------------------------------- 1 | # 单例模式 2 | ### 主要内容 3 | 属于创建型的设计模式 4 | 5 | 保证一个类仅有一个实例,并提供一个访问它的全局访问点。 6 | 7 | ![单例模式的UML类图](../.gitbook/assets/singleuml.png) 8 | ### 代码例子 9 | 解决的问题: 10 | 11 | 很多时候我们都要保证一个类只有一个实例 12 | 13 | #### 懒汉式: 14 | ![懒汉式](../.gitbook/assets/singlelazy.png) 15 | 16 | #### 饿汉式: 17 | ![饿汉式](../.gitbook/assets/singlehungry.png) 18 | 19 | #### 懒汉式+同步锁: 20 | ![懒汉式+同步锁](../.gitbook/assets/singlehungryandlock.png) 21 | 22 | #### 测试代码: 23 | 无 24 | 25 | ### 总结 26 | ![总结](../.gitbook/assets/singleissue.png) -------------------------------------------------------------------------------- /10种设计模式/工厂模式.md: -------------------------------------------------------------------------------- 1 | # 工厂模式 2 | ### 主要内容 3 | 属于创建型的设计模式 4 | 5 | ![工厂模式的UML类图](../.gitbook/assets/factoryuml.png) 6 | ### 代码例子 7 | 模拟一个可以卖出不同口味的pizza店,比萨店经营有成,接下来的计划就是在多个不同城市开设加盟店 8 | 9 | 需要建立一个框架,把PizzaStore和创建Pizza捆绑在一起, 同时又保持 10 | 一定的弹性。 11 | 12 | #### pizza(为抽象类): 13 | ![pizza](../.gitbook/assets/factorypizza.png) 14 | 15 | #### pizza的各个子类: 16 | ![pizza](../.gitbook/assets/factorypizzaclass.png) 17 | 18 | #### 工厂(抽象): 19 | ![factory](../.gitbook/assets/factoryfactory.png) 20 | 21 | #### 具体工厂: 22 | ![factory](../.gitbook/assets/factoryfactoryclass.png) 23 | 24 | #### 测试代码: 25 | ![test](../.gitbook/assets/factorytest.png) 26 | 27 | ### 总结 28 | 29 | 1. 通过扩展来新增具体类的,符合开闭原则,但是在客户端就必须要感知到具体的工厂类, 30 | 也就是将判断逻辑由简单工厂的工厂类挪到客户端。 31 | 2. 工厂模式横向扩展很方便,假如又有新区域的加盟店,那么只需要创建相应的披萨店子 32 | 类和披萨子类去实现抽象工厂接口和抽象产品接口即可,而不用去修改原有已经存在的代码。 -------------------------------------------------------------------------------- /10种设计模式/抽象工厂模式.md: -------------------------------------------------------------------------------- 1 | # 抽象工厂模式 2 | ### 主要内容 3 | 属于创建型的设计模式 4 | 5 | ![抽象工厂模式的UML类图](../.gitbook/assets/abstractfactoryuml.png) 6 | ### 代码例子 7 | 模拟各大厂商不同品牌产品的加工,其中一种产品称为产品等级(如手机),一个产生不同的产品等级的厂商为产品族 8 | 9 | #### 手机: 10 | ![iphone](../.gitbook/assets/abstractfactoryiphone.png) 11 | 12 | #### 手机实现类: 13 | ![iphone](../.gitbook/assets/abstractfactoryiphoneclass.png) 14 | 15 | #### 路由器 16 | ![router](../.gitbook/assets/abstractfactoryrouter.png) 17 | 18 | #### 路由器实现类: 19 | ![router](../.gitbook/assets/abstractfactoryrouterclass.png) 20 | 21 | #### 厂商(抽象)) 22 | ![factory](../.gitbook/assets/abstractfactoryfactory.png) 23 | 24 | #### 厂商: 25 | ![factory](../.gitbook/assets/abstractfactoryfactoryclass.png) 26 | 27 | #### 测试代码: 28 | ![test](../.gitbook/assets/abstractfactorytest.png) 29 | 30 | ### 总结 31 | ![issue](../.gitbook/assets/abstractfactoryissue.png) 32 | -------------------------------------------------------------------------------- /10种设计模式/数据访问对象模式.md: -------------------------------------------------------------------------------- 1 | # 数据访问对象模式 2 | 3 | 简称DAO,该模式不是GOF23种模式之一。 4 | 5 | 重点在于把**数据访问的操作与业务分离**,实现对**数据库等资源的各种操作**。常用的数据操作比如增删查改都可以放在DAO层。 6 | 7 | ![数据层用于分离业务层和资源层](../.gitbook/assets/764_b12_512.png) 8 | 9 | 包含**3个参与者**:数据访问对象接口、数据访问对象实体类、模型对象/数值对象。 10 | 11 | ![](../.gitbook/assets/image.png) 12 | 13 | **数据访问对象接口:**该接口定义了在一个模型对象上要执行的标准操作。 14 | 15 | **数据访问对象实体类:**该类实现了上述的接口,负责从数据源获取数据,数据源可以是数据库,也可以是 xml,或者是其他的存储机制。 16 | 17 | **模型对象/数值对象:**该对象是简单的普通对象,包含了 get/set 方法来存储通过使用 DAO 类检索到的数据。 18 | 19 | ### 数据访问对象模式总结 20 | 21 | ![](../.gitbook/assets/1649214424\(1\).png) 22 | -------------------------------------------------------------------------------- /10种设计模式/模板模式.md: -------------------------------------------------------------------------------- 1 | # 模板模式 2 | ### 主要内容 3 | 行为型设计模式 4 | 5 | ![UML类图](../.gitbook/assets/templateuml.png) 6 | ### 代码例子 7 | 用模板方法实现红豆奶茶制作 8 | 9 | #### 模板类(抽象): 10 | ![soymilk](../.gitbook/assets/templatesoymilk.png) 11 | 12 | #### 实现的模板: 13 | ![redmilk](../.gitbook/assets/templateredmilk.png) 14 | 15 | 16 | #### 测试代码: 17 | ![test](../.gitbook/assets/templatetest.png) 18 | 19 | ### 总结 20 | 模板方法导致一种反向控制结构 21 | 22 | 指的是父类调用一个子类的操作,而不是相反 23 | 24 | 有时被称为“好莱坞法则”,即“别找我们。我们找你” 25 | -------------------------------------------------------------------------------- /10种设计模式/生产者消费者模式.md: -------------------------------------------------------------------------------- 1 | # 生产者消费者模式 2 | ### 主要内容 3 | 不属于GOF设计模式 4 | 5 | ![UML类图](../.gitbook/assets/productuml.png) 6 | ### 代码例子 7 | 8 | #### 缓冲区: 9 | ![buffer](../.gitbook/assets/productbuffer1.png) 10 | 11 | ![buffer](../.gitbook/assets/productbuffer2.png) 12 | 13 | 14 | #### 生产者: 15 | ![producer](../.gitbook/assets/productproducer.png) 16 | 17 | #### 消费者: 18 | ![producer](../.gitbook/assets/productcomsumer.png) 19 | 20 | #### 测试代码: 21 | ![producer](../.gitbook/assets/producttest.png) 22 | 23 | ### 总结 24 | ![issue](../.gitbook/assets/productissue.png) 25 | -------------------------------------------------------------------------------- /10种设计模式/策略模式.md: -------------------------------------------------------------------------------- 1 | # 策略模式 2 | 3 | ### 主要内容 4 | 5 | 属于行为型的设计模式。 6 | 7 | 重点对**策略进行抽象**,策略之间**互相独立**,可以互相替换,使得算法与客户分开。主要由是**3个参与者**:抽象策略类(策略接口)、具体策略类、环境类(策略使用类)。 8 | 9 | ![策略模式UML类图](../.gitbook/assets/1648910128\(1\).png) 10 | 11 | ### 代码例子 12 | 13 | 下面举一个例子,我们想要实现超市销售商品的价格计算函数。对不同类型的用户价格的计算方式不一样。 14 | 15 | 算法一:对初级会员没有折扣。 16 | 17 | 算法二:对中级会员提供10%的促销折扣。 18 | 19 | 算法三:对高级会员提供20%的促销折扣。 20 | 21 | #### **我们首先设计抽象策略:** 22 | 23 | ``` 24 | package strategy; 25 | public interface MemberStrategy { 26 | /** * 计算图书的价格 27 | * @param booksPrice 图书的原价 28 | * @return 计算出打折后的价格 29 | */ 30 | public double calcPrice(double booksPrice); 31 | } 32 | ``` 33 | 34 | #### **接着实现两个具体策略类:** 35 | 36 | 实现第一个具体策略类: 37 | 38 | ``` 39 | package strategy; 40 | public class AdvancedMemberStrategy implements MemberStrategy{ 41 | @Override 42 | public double calcPrice(double booksPrice) { 43 | System.out.println("对于高级会员的折扣为20%"); 44 | return booksPrice * 0.8; 45 | } 46 | } 47 | ``` 48 | 49 | 实现第二个具体策略类: 50 | 51 | ``` 52 | package strategy; 53 | public class PrimaryMemberStrategy implements MemberStrategy{ 54 | @Override 55 | public double calcPrice(double booksPrice) { 56 | System.out.println("对于初级会员的没有折扣"); 57 | return booksPrice; 58 | } 59 | } 60 | ``` 61 | 62 | #### **最后实现环境类:** 63 | 64 | ``` 65 | package strategy; 66 | public class Price { 67 | private MemberStrategy strategy; 68 | /** 69 | * 构造函数,传入一个具体的策略对象 70 | * @param strategy 具体的策略对象 71 | */ 72 | public Price(MemberStrategy strategy){ 73 | this.strategy = strategy; 74 | } 75 | /** 76 | *计算图书的价格 77 | * @param booksPrice 图书的原价 78 | * @return 计算出打折后的价格 79 | */ 80 | public double quote(double booksPrice){ 81 | return this.strategy.calcPrice(booksPrice); 82 | } 83 | } 84 | ``` 85 | 86 | **测试的代码如下:** 87 | 88 | ``` 89 | package strategy; 90 | public class Client { 91 | public static void main(String[] args) { 92 | //选择并创建需要使用的策略对象 93 | MemberStrategy strategy = new AdvancedMemberStrategy(); 94 | //创建环境 95 | Price price = new Price(strategy); 96 | //计算价格 97 | double quote = price.quote(300); 98 | System.out.println("图书的最终价格为:" + quote); 99 | } 100 | } 101 | ``` 102 | 103 | ### 策略模式总结 104 | 105 | ![](../.gitbook/assets/1648910902.png) 106 | -------------------------------------------------------------------------------- /10种设计模式/简单工厂模式.md: -------------------------------------------------------------------------------- 1 | # 简单工厂模式 2 | ### 主要内容 3 | 属于创建型的设计模式 4 | 5 | 简单工厂模式 (SimpleFactory Pattern) 并不是一个真正意义上设计模式,但工 6 | 厂模式是建立在它之上。 7 | 8 | ![简单工厂模式的UML类图](../.gitbook/assets/simplefactoryuml.png) 9 | ### 代码例子 10 | 模拟一个可以卖出不同口味的pizza店 11 | 12 | #### pizza的父类(为抽象类): 13 | ![pizzaa](../.gitbook/assets/simplefactorypizza.png) 14 | 15 | #### pizza的各个子类: 16 | ![pizza](../.gitbook/assets/greekpizza.png) 17 | 18 | #### 工厂: 19 | ![simplefactory](../.gitbook/assets/simplefactorypizzafactory.png) 20 | 21 | #### 测试代码: 22 | 23 | ### 总结: 24 | 25 | 创建对象的逻辑判断放在了工厂类中,客户不感知具体的类,但是其违背了开闭原则, 26 | 如果要增加新的披萨类型,就必须修改工厂类。 -------------------------------------------------------------------------------- /10种设计模式/观察者模式.md: -------------------------------------------------------------------------------- 1 | # 观察者模式 2 | ### 主要内容 3 | 行为型设计模式 4 | 5 | ![简单工厂模式的UML类图](../.gitbook/assets/observerTest.png) 6 | ### 代码例子 7 | 假设猫是老鼠和狗的观察目标,老鼠和狗是观察者,猫叫老鼠跑,狗也 8 | 跟着叫,使用观察者模式描述该过程。 9 | 10 | #### 观察者(抽象): 11 | ![观察者](../.gitbook/assets/observerobserver.png) 12 | 13 | #### 被观察者(抽象): 14 | ![被观察者](../.gitbook/assets/observerobservered.png) 15 | 16 | #### 猫: 17 | ![猫](../.gitbook/assets/observercat.png) 18 | 19 | #### 狗子: 20 | ![狗](../.gitbook/assets/observerdog.png) 21 | 22 | #### 老鼠: 23 | ![老鼠](./.gitbook/assets/observermouse.png) 24 | 25 | #### 测试代码: 26 | ![testit](./.gitbook/assets/observertestit.png) 27 | 28 | ### 总结 29 | ![issue](../.gitbook/assets/observerissue.png) -------------------------------------------------------------------------------- /10种设计模式/迭代器模式.md: -------------------------------------------------------------------------------- 1 | # 迭代器模式 2 | 3 | ### 主要内容 4 | 5 | 属于行为型的设计模式。 6 | 7 | 重点是将聚合对象的**存储和遍历行为分离**,提供多种迭代聚合对象中数据的方法。迭代器方法是GOF23中设计模式中最为常用的方法,便于对各种集合类型遍历。 8 | 9 | 主要包含**4个参与者**,包含抽象聚集类、具体聚集类、抽象迭代器类(或者接口)和具体迭代器类。 10 | 11 | ![迭代器模式UML类图](../.gitbook/assets/1648911234\(1\).png) 12 | 13 | ### 代码例子 14 | 15 | **首先实现聚集抽象类:** 16 | 17 | ``` 18 | package iteratorTest; 19 | //Aggregate聚集抽象类 20 | public interface Aggregate { 21 | //添加 22 | void add(Object object); 23 | //创建迭代器 24 | Iterator createIterator(); 25 | } 26 | ``` 27 | 28 | **实现具体聚集类:** 29 | 30 | ``` 31 | package iteratorTest; 32 | import java.util.*; 33 | //ConcreteAggregate集体聚集类,继承Aggregate 34 | public class ConcreteAggregate implements Aggregate { 35 | private List items = new ArrayList<>(); 36 | @Override 37 | public Iterator createIterator() { 38 | return new ConcreteIterator(items); 39 | } 40 | public void add(Object object) { 41 | items.add(object); 42 | } 43 | } 44 | ``` 45 | 46 | **实现迭代器接口:** 47 | 48 | ``` 49 | package iteratorTest; 50 | //Iterator迭代器接口类 51 | public interface Iterator { 52 | //两个重要的方法 53 | //得到下一个对象 54 | Object next(); 55 | //判断是否有下一个对象 56 | boolean hasNext(); 57 | } 58 | ``` 59 | 60 | **实现具体迭代器:** 61 | 62 | ``` 63 | package iteratorTest; 64 | import java.util.*; 65 | //ConcreteIterator具体迭代器类,实现Iterator 66 | public class ConcreteIterator implements Iterator { 67 | private List list; 68 | private int currentIndex = 0; 69 | public ConcreteIterator(List list) { 70 | this.list = list; 71 | } 72 | @Override 73 | public Object next() { 74 | if (hasNext()) { 75 | return list.get(currentIndex++); 76 | } 77 | return null; 78 | } 79 | 80 | @Override 81 | public boolean hasNext() { 82 | if (currentIndex == list.size()) { 83 | return false; 84 | } 85 | return true; 86 | } 87 | } 88 | ``` 89 | 90 | **最后测试迭代器模式:** 91 | 92 | ``` 93 | package iteratorTest; 94 | import java.util.*; 95 | public class IteratorTest { 96 | public static void main(String[] args) { 97 | Aggregate aggregate = new ConcreteAggregate(); 98 | aggregate.add(1); 99 | aggregate.add(2); 100 | aggregate.add(3); 101 | aggregate.add(4); 102 | 103 | Iterator iterator = aggregate.createIterator(); 104 | while (iterator.hasNext()) { 105 | System.out.println(iterator.next()); 106 | } 107 | } 108 | 109 | } 110 | ``` 111 | 112 | ### 迭代器模式总结 113 | 114 | ![](../.gitbook/assets/1648911669\(1\).png) 115 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JavaCodeExamples 2 | The repository includes some examples of the Java course. You're welcome to modify and add examples. 3 | 4 | 第二章:java语言基础[src](https://github.com/cuiyungao/JavaCodeExamples/tree/master/src) 5 | 6 | 第三章:类和对象[src3](https://github.com/cuiyungao/JavaCodeExamples/tree/master/src3) 7 | 8 | 第四章:接口与继承[src4](https://github.com/cuiyungao/JavaCodeExamples/tree/master/src4) 9 | 10 | 第五章:设计模式导论(单例模式,三种工厂模式)[src5](https://github.com/cuiyungao/JavaCodeExamples/tree/master/src5) 11 | 12 | 第六章:软件测试及代码质量保障[src6](https://github.com/cuiyungao/JavaCodeExamples/tree/master/src6) 13 | 14 | 第七章:集合与策略模式、迭代器模式[src7](https://github.com/cuiyungao/JavaCodeExamples/tree/master/src7) 15 | 16 | 第八章:数据访问对象模式、输入输出流[src8](https://github.com/cuiyungao/JavaCodeExamples/tree/master/src8) 17 | 18 | 第九章:MVC、Swing图形用户界面[src9](https://github.com/cuiyungao/JavaCodeExamples/tree/master/src9) 19 | 20 | 第十章:Thread、生产者与消费者模式[src10](https://github.com/cuiyungao/JavaCodeExamples/tree/master/src10) 21 | 22 | 第十一章:泛型与反射、模板模式[src11](https://github.com/cuiyungao/JavaCodeExamples/tree/master/src11) 23 | 24 | 第十二章:网络编程、观察者模式[src12](https://github.com/cuiyungao/JavaCodeExamples/tree/master/src12) 25 | 26 | Good luck! 27 | -------------------------------------------------------------------------------- /src/InputTest.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.IOException; 3 | import java.io.InputStreamReader; 4 | import java.util.Scanner; 5 | 6 | //jdk15 7 | public class InputTest { 8 | public static void main(String[] args) { 9 | //方法一 10 | BufferedReader stdin1=new BufferedReader(new InputStreamReader(System.in)); 11 | String str; 12 | try { 13 | System.out.print("请输入:"); 14 | str = stdin1.readLine();//此处会出现io异常,使用try catch捕获 15 | System.out.println("您的输入是:"+str); 16 | //stdin1.close();这里本该关闭的,但是这里的关闭代码会关闭System.in使得后续的scanner无法使用System.in,详情可以在idea中 17 | //长按ctrl用鼠标单击close查看源代码 18 | } catch (IOException e) { 19 | e.printStackTrace(); 20 | } 21 | //========================================================================= 22 | //方法二 23 | Scanner stdin2=new Scanner(System.in); 24 | System.out.print("请输入:"); 25 | String str2=stdin2.next();//关于这里为什么不需要捕获异常:https://qa.1r1g.com/sf/ask/1908502291/ 26 | System.out.println("您的输入是:"+str2); 27 | stdin2.close();//进行关闭操作方便JVM对对象资源进行管理 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.InputMismatchException; 3 | import java.util.Scanner; 4 | 5 | 6 | public class Main { 7 | 8 | public static void main(String[] args) { 9 | // 冒泡排序 10 | // int[] a = {2, 6, 1, 7, 0}; 11 | // Sort.sortBubble(a); 12 | // System.out.println(Arrays.toString(a)); 13 | 14 | // 理解构造方法和this的用法 15 | // Person per = new Person("张三", 190.3f); 16 | // per.name = "张三"; 17 | // per.age = -30; 18 | // per.tell(); 19 | 20 | //理解异常机制 21 | double score; 22 | Scanner input = new Scanner(System.in); 23 | System.out.println("请输入你的考试成绩:"); 24 | try { 25 | score = input.nextDouble(); // 获取成绩 26 | if(score < 0) { 27 | throw new MyException("成绩为负!"); 28 | } else if(score > 100) { 29 | throw new MyException("你的优秀已经溢出了!"); 30 | } else { 31 | System.out.println("你的成绩为:"+score); 32 | } 33 | } catch(InputMismatchException e1) { 34 | System.out.println("输入的成绩不是数字!"); 35 | } catch(MyException e2) { 36 | System.out.println(e2.getMessage()); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/MyException.java: -------------------------------------------------------------------------------- 1 | public class MyException extends Exception{ 2 | public MyException(){ 3 | super(); 4 | } 5 | 6 | public MyException(String str){ 7 | super(str); 8 | } 9 | 10 | } -------------------------------------------------------------------------------- /src/Person.java: -------------------------------------------------------------------------------- 1 | public class Person { 2 | String name; 3 | int age; 4 | float height; 5 | 6 | public void tell(){ 7 | System.out.println("姓名:" + name + ",年龄:" + age); 8 | } 9 | 10 | public void eat(){ 11 | System.out.println("I'm eating"); 12 | } 13 | 14 | public void daily(){ 15 | this.eat(); 16 | System.out.println("I'm studying"); 17 | } 18 | 19 | public Person(){ 20 | 21 | } 22 | 23 | public Person(String name){ 24 | this.name = name; 25 | this.tell(); 26 | } 27 | 28 | public Person(String name, float height){ 29 | this(name); 30 | this.height = height; 31 | System.out.println("他也很高" + height); 32 | } 33 | } 34 | 35 | 36 | -------------------------------------------------------------------------------- /src/Sort.java: -------------------------------------------------------------------------------- 1 | public class Sort { 2 | 3 | public static void sortBubble(int[] a) { 4 | //外层循环控制比较的次数 5 | for (int i = 0; i < a.length - 1; i++) { 6 | //内层循环控制到达位置 7 | for (int j = 0; j < a.length - i - 1; j++) { 8 | //前面的元素比后面大就交换 9 | if (a[j] > a[j + 1]) { 10 | int temp = a[j]; 11 | a[j] = a[j + 1]; 12 | a[j + 1] = temp; 13 | } 14 | } 15 | } 16 | } 17 | 18 | } 19 | 20 | -------------------------------------------------------------------------------- /src/Type.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Type { 5 | 6 | public static void main(String[] args) { 7 | // 类型提升例子 8 | // int n = 5; 9 | // double d1 = (1.2 + 24.0)/n; 10 | // double d2 = 1.2 + 24 / 5; 11 | // double d3 = 24 / 5; 12 | // 13 | // Typetester t = new Typetester(); 14 | // System.out.println(d1); 15 | // t.printType(d1); 16 | // System.out.println(d2); 17 | // t.printType(d2); 18 | // System.out.println(d3); 19 | // t.printType(d3); 20 | // t.printType(24/5); 21 | 22 | //类型转换 -- 损失精度 23 | // int a = 123456789; 24 | // float f = a; 25 | // System.out.println(f); 26 | 27 | //字符串转换为数值 28 | // int x1 = Integer.parseInt("260"); 29 | // float y = Float.parseFloat("23.5"); 30 | // double z = Double.parseDouble("45.6"); 31 | // System.out.printf("%d %.2f %.2f", x1, y, z); // 沿用C语言函数库中的printf方法 32 | 33 | //常量的声明 34 | // final double CM_PER_INCH = 2.54; 35 | 36 | // 标准输入 37 | Scanner in = new Scanner(System.in); 38 | System.out.print("What is your name?"); 39 | String name = in.nextLine(); 40 | System.out.print("What is your student ID?"); 41 | int id = in.nextInt(); //nextDouble 42 | System.out.println("Hello, "+name+", id " + id); 43 | 44 | //数组 45 | // int[] a = new int[5]; 46 | // System.out.println(a.getClass().getName()); 47 | // String[][] d = new String[5][5]; 48 | // int[] d_new = new int[]{0,1}; 49 | // System.out.println(d.getClass().getName()); 50 | // System.out.println(Arrays.toString(d_new)); 51 | 52 | } 53 | } 54 | 55 | class Typetester { 56 | void printType(byte x) { 57 | System.out.println(x + " is an byte"); 58 | } 59 | void printType(int x) { 60 | System.out.println(x + " is an int"); 61 | } 62 | void printType(float x) { 63 | System.out.println(x + " is an float"); 64 | } 65 | void printType(double x) { 66 | System.out.println(x + " is an double"); 67 | } 68 | void printType(char x) { 69 | System.out.println(x + " is an char"); 70 | } 71 | } -------------------------------------------------------------------------------- /src/Welcome.java: -------------------------------------------------------------------------------- 1 | public class Welcome { 2 | public static void main(String[] args) 3 | { 4 | String greeting = "Welcome to Java!"; 5 | System.out.println(greeting); 6 | for (int i = 0; i < greeting.length(); i++) 7 | System.out.print("="); 8 | System.out.println(); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src10/prodconsumer/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /src10/prodconsumer/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src10/prodconsumer/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src10/prodconsumer/Buffer.java: -------------------------------------------------------------------------------- 1 | package prodconsumer; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Buffer { 7 | private List data = new ArrayList<>(); 8 | private static final int MAX = 2; 9 | private static final int MIN = 0; 10 | 11 | public void put(int value){ 12 | while (true){ 13 | try { 14 | //sleep不能放在同步代码块里面,因为sleep不会释放锁, 15 | // 当前线程会一直占有produce线程,直到达到容量,调用wait()方法主动释放锁 16 | Thread.sleep(500); 17 | } catch (InterruptedException e) { 18 | e.printStackTrace(); 19 | } 20 | synchronized (this){ 21 | //当容器满的时候,producer处于等待状态 22 | while (data.size() == MAX){ 23 | System.out.println("buffer is full,waiting ...."); 24 | try { 25 | wait(); //producer处于等待状态 26 | } catch (InterruptedException e) { 27 | e.printStackTrace(); 28 | } 29 | } 30 | //没有满,则继续produce 31 | System.out.println("producer--"+ Thread.currentThread().getName()+"--put:" + value); 32 | data.add(value); 33 | //唤醒其他所有处于wait()的线程,包括消费者和生产者 34 | notifyAll(); 35 | } 36 | } 37 | } 38 | 39 | public Integer take(){ 40 | Integer val = 0; 41 | while (true){ 42 | try { 43 | Thread.sleep(500); 44 | } catch (InterruptedException e) { 45 | e.printStackTrace(); 46 | } 47 | synchronized (this){ 48 | //如果容器中没有数据,consumer处于等待状态 49 | while (data.size() == MIN){ 50 | System.out.println("buffer is empty,waiting ..."); 51 | try { 52 | wait(); 53 | } catch (InterruptedException e) { 54 | e.printStackTrace(); 55 | } 56 | } 57 | //如果有数据,继续consume 58 | val = data.remove(0) ; 59 | System.out.println("consumer--"+ Thread.currentThread().getName()+"--take:" + val); 60 | 61 | //唤醒其他所有处于wait()的线程,包括消费者和生产者 62 | //notify必须放在同步代码块里面 63 | notifyAll(); 64 | } 65 | } 66 | 67 | 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src10/prodconsumer/Consumer.java: -------------------------------------------------------------------------------- 1 | package prodconsumer; 2 | 3 | public class Consumer implements Runnable{ 4 | private Buffer buffer; 5 | public Consumer(Buffer buffer) { 6 | this.buffer = buffer; 7 | } 8 | 9 | @Override 10 | public void run() { 11 | Integer val = buffer.take(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src10/prodconsumer/Main.java: -------------------------------------------------------------------------------- 1 | package prodconsumer; 2 | 3 | public class Main { 4 | public static void main(String[] args){ 5 | Buffer buffer = new Buffer(); 6 | 7 | Thread producer1 = new Thread(new Producer(buffer)); 8 | Thread producer2 = new Thread(new Producer(buffer)); 9 | Thread producer3 = new Thread(new Producer(buffer)); 10 | producer1.start(); 11 | producer2.start(); 12 | producer3.start(); 13 | 14 | Thread consumer1 = new Thread(new Consumer(buffer)); 15 | Thread consumer2 = new Thread(new Consumer(buffer)); 16 | Thread consumer3 = new Thread(new Consumer(buffer)); 17 | consumer1.start(); 18 | consumer2.start(); 19 | consumer3.start(); 20 | 21 | } 22 | } -------------------------------------------------------------------------------- /src10/prodconsumer/Producer.java: -------------------------------------------------------------------------------- 1 | package prodconsumer; 2 | import java.util.Random; 3 | 4 | public class Producer implements Runnable{ 5 | private Buffer buffer; 6 | public Producer(Buffer buffer) { 7 | this.buffer = buffer; 8 | } 9 | @Override 10 | public void run() { 11 | buffer.put(new Random().nextInt(10)); 12 | } 13 | } -------------------------------------------------------------------------------- /src10/thread/AddDec.java: -------------------------------------------------------------------------------- 1 | package thread; 2 | 3 | public class AddDec { 4 | public static void main(String[] args) throws Exception { 5 | AddThread add = new AddThread(); 6 | add.start(); 7 | // add.join(); //要等待add结束之后,后面的才开始执行 8 | //使用interrupt中断方法 9 | // Thread.sleep(200); 10 | // add.interrupt(); 11 | 12 | DecThread dect = new DecThread(); 13 | Thread dec = new Thread(dect); 14 | dec.start(); 15 | // dec.join(); //要等待dec结束之后,后面的才开始执行 16 | 17 | 18 | //使用Lambda表达式创建并启动线程 19 | Runnable r = () -> {System.out.println("Thread: Runnable with Lambda Expression");}; 20 | Thread lamt = new Thread(r); 21 | lamt.start(); 22 | // lamt.stop();//stop()方法已被废弃 23 | 24 | //设置优先级 25 | System.out.println("------------设置优先级------------"); 26 | Runnable r1 = () -> {System.out.println("Thread: Low priority");}; 27 | Runnable r2 = () -> {System.out.println("Thread: high priority");}; 28 | Thread tr1 = new Thread(r1); 29 | Thread tr2 = new Thread(r2); 30 | tr1.setPriority(1); 31 | tr2.setPriority(10); 32 | tr1.start(); 33 | tr2.start(); 34 | 35 | } 36 | } 37 | 38 | //class Counter { 39 | // public static int count = 0; 40 | //} 41 | 42 | class AddThread extends Thread { 43 | public void run() { 44 | if (!Thread.interrupted()) { //中断的方法之一 45 | for (int i = 0; i < 10; i++) { 46 | try { 47 | Thread.sleep(100); 48 | } catch (InterruptedException e) { 49 | e.printStackTrace(); 50 | break; 51 | } 52 | // Counter.count += 1; 53 | System.out.println(Thread.currentThread().getName() + "--AddThread-- " + i); 54 | } 55 | } 56 | } 57 | } 58 | 59 | class DecThread implements Runnable { 60 | public void run() { 61 | for (int i=0; i<10; i++) { 62 | // Counter.count -= 1; 63 | System.out.println(Thread.currentThread().getName()+"--DecThread-- "+ i);} 64 | } 65 | } 66 | 67 | -------------------------------------------------------------------------------- /src10/thread/DeadLock.java: -------------------------------------------------------------------------------- 1 | package thread; 2 | 3 | public class DeadLock { 4 | public static String bluekey = "Blue Key"; 5 | public static String redkey = "Red Key"; 6 | public static void main(String[] args) { 7 | PerA la = new PerA(); 8 | new Thread(la).start(); 9 | PerB lb = new PerB(); 10 | new Thread(lb).start(); 11 | } 12 | } 13 | class PerA implements Runnable{ 14 | public void run() { 15 | try { 16 | while(true){ 17 | synchronized (DeadLock.bluekey) { 18 | System.out.println(" PerA lock blue key"); 19 | Thread.sleep(3000); // 此处等待是给B能锁住机会 20 | synchronized (DeadLock.redkey) { 21 | System.out.println(" PerA open door"); 22 | Thread.sleep(60 * 1000); // 为测试,占用了就不放 23 | } 24 | } 25 | } 26 | } catch (Exception e) { 27 | e.printStackTrace(); 28 | } 29 | } 30 | } 31 | class PerB implements Runnable{ 32 | public void run() { 33 | try { 34 | while(true){ 35 | synchronized (DeadLock.redkey) { 36 | System.out.println(" PerB lock red key"); 37 | Thread.sleep(3000); // 此处等待是给A能锁住机会 38 | synchronized (DeadLock.bluekey) { 39 | System.out.println(" PerB open door"); 40 | Thread.sleep(60 * 1000); // 为测试,占用了就不放 41 | } 42 | } 43 | } 44 | } catch (Exception e) { 45 | e.printStackTrace(); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /src10/thread/DeadLockExample2.java: -------------------------------------------------------------------------------- 1 | package thread; 2 | 3 | import java.util.TreeMap; 4 | 5 | public class DeadLockExample2 implements Runnable{ 6 | public int flag = 1; 7 | static Object o1= new Object(), o2 = new Object(); 8 | 9 | public void run(){ 10 | System.out.println("flag=" + flag); 11 | 12 | if(flag==1){ 13 | synchronized (o1){ 14 | try{ 15 | Thread.sleep(500); 16 | }catch (Exception e){ 17 | e.printStackTrace(); 18 | } 19 | 20 | //只要锁住o2就完成执行 21 | synchronized (o2){ 22 | System.out.println(Thread.currentThread().getName() + "----完成"); 23 | } 24 | } 25 | } 26 | 27 | if(flag==0){ 28 | synchronized (o2){ 29 | try{ 30 | Thread.sleep(500); 31 | }catch (Exception e){ 32 | e.printStackTrace(); 33 | } 34 | 35 | //只要锁住o1就完成执行 36 | synchronized (o1){ 37 | System.out.println(Thread.currentThread().getName() + "----完成"); 38 | } 39 | } 40 | } 41 | } 42 | 43 | public static void main(String[] args) { 44 | DeadLockExample2 dl1 = new DeadLockExample2(); 45 | DeadLockExample2 dl2 = new DeadLockExample2(); 46 | dl1.flag = 1; 47 | dl2.flag = 0; 48 | //开启两个线程 49 | Thread t1 = new Thread(dl1); 50 | Thread t2 = new Thread(dl2); 51 | t1.start(); 52 | t2.start(); 53 | } 54 | } 55 | 56 | 57 | -------------------------------------------------------------------------------- /src10/thread/FutureDemo.java: -------------------------------------------------------------------------------- 1 | package thread; 2 | import java.util.concurrent.*; //Future、Callable方法如下 3 | 4 | public class FutureDemo { 5 | public static void main(String[] args) { 6 | ExecutorService executor = Executors.newCachedThreadPool(); //ExecutorService继承了Executor接口,是真正的线程池接口 7 | Task task = new Task(); 8 | Future result = executor.submit(task); 9 | executor.shutdown(); 10 | 11 | try { 12 | Thread.sleep(1000); 13 | } catch (InterruptedException e1) { 14 | e1.printStackTrace(); 15 | } 16 | 17 | System.out.println("主线程在执行任务"); 18 | 19 | try { 20 | System.out.println("task运行结果"+result.get()); 21 | } catch (InterruptedException e) { 22 | e.printStackTrace(); 23 | } catch (ExecutionException e) { 24 | e.printStackTrace(); 25 | } 26 | 27 | System.out.println("所有任务执行完毕"); 28 | } 29 | } 30 | 31 | class Task implements Callable { 32 | @Override 33 | public Integer call() throws Exception { 34 | System.out.println("子线程在进行计算"); 35 | Thread.sleep(3000); 36 | int sum = 0; 37 | for(int i=0;i<100;i++){ 38 | sum += i; 39 | } 40 | return sum; 41 | } 42 | } -------------------------------------------------------------------------------- /src10/thread/FutureTaskDemo.java: -------------------------------------------------------------------------------- 1 | package thread; 2 | 3 | import java.util.concurrent.*; 4 | 5 | public class FutureTaskDemo { 6 | public static void main(String[] args) { 7 | //第一种方式 8 | ExecutorService executor = Executors.newCachedThreadPool(); 9 | Task task = new Task(); 10 | FutureTask futureTask = new FutureTask(task); 11 | executor.submit(futureTask); 12 | executor.shutdown(); 13 | 14 | //第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread 15 | /*Task task = new Task(); 16 | FutureTask futureTask = new FutureTask(task); 17 | Thread thread = new Thread(futureTask); 18 | thread.start();*/ 19 | 20 | try { 21 | Thread.sleep(1000); 22 | } catch (InterruptedException e1) { 23 | e1.printStackTrace(); 24 | } 25 | 26 | System.out.println("主线程在执行任务"); 27 | 28 | try { 29 | System.out.println("task运行结果"+futureTask.get()); 30 | } catch (InterruptedException e) { 31 | e.printStackTrace(); 32 | } catch (ExecutionException e) { 33 | e.printStackTrace(); 34 | } 35 | 36 | System.out.println("所有任务执行完毕"); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src10/thread/InterruptTest.java: -------------------------------------------------------------------------------- 1 | package thread; 2 | 3 | public class InterruptTest { 4 | public static void main(String[] args) throws Exception 5 | { 6 | Runnable runnable = new Runnable() 7 | { 8 | public void run() 9 | { 10 | while (true) 11 | { 12 | if (Thread.currentThread().isInterrupted()) 13 | { 14 | System.out.println("线程被中断了"); 15 | System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted()); 16 | return ; 17 | } 18 | else 19 | { 20 | System.out.println("线程没有被中断"); 21 | } 22 | } 23 | } 24 | }; 25 | Thread t = new Thread(runnable); 26 | t.start(); 27 | Thread.sleep(3000); 28 | t.interrupt(); 29 | System.out.println("线程中断了,程序到这里了"); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src10/thread/RunnableVSThread.java: -------------------------------------------------------------------------------- 1 | package thread; 2 | 3 | 4 | public class RunnableVSThread { 5 | public static void main(String[] args) throws Exception { 6 | //Runnable多线程共享一个对象 7 | TestRunnable tr = new TestRunnable(); 8 | Thread td1= new Thread(tr); 9 | td1.start(); 10 | Thread.sleep(200); 11 | 12 | Thread td2 = new Thread(tr); 13 | td2.start(); 14 | Thread.sleep(200); 15 | 16 | Thread td3 = new Thread(tr); 17 | td3.start(); 18 | Thread.sleep(200); 19 | 20 | //继承Thread则为每个线程创建一个实例对象 21 | TestThread tt1 = new TestThread(); 22 | tt1.start(); 23 | Thread.sleep(200); 24 | 25 | TestThread tt2 = new TestThread(); 26 | tt2.start(); 27 | Thread.sleep(200); 28 | 29 | TestThread tt3 = new TestThread(); 30 | tt3.start(); 31 | Thread.sleep(200); 32 | } 33 | } 34 | 35 | class TestRunnable implements Runnable { 36 | private int counter = 3; 37 | 38 | public void run(){ 39 | counter--; 40 | System.out.println(Thread.currentThread().getName()+"--Runnable--"+counter); 41 | } 42 | } 43 | 44 | class TestThread extends Thread { 45 | private int counter = 3; 46 | 47 | @Override 48 | public void run() { 49 | counter--; 50 | System.out.println(Thread.currentThread().getName()+"--Thread--"+counter); 51 | } 52 | } -------------------------------------------------------------------------------- /src10/thread/SetDaemonDemo.java: -------------------------------------------------------------------------------- 1 | package thread; 2 | 3 | public class SetDaemonDemo extends Thread{ 4 | public SetDaemonDemo(String name){ 5 | super(name); 6 | } 7 | 8 | @Override 9 | public void run() { 10 | while (true){ 11 | System.out.println(getName() + "----运行----"); 12 | } 13 | } 14 | 15 | public static void main(String[] args) { 16 | SetDaemonDemo sd = new SetDaemonDemo("Thread 1"); 17 | //设置sd为守护进程,在主程序结束后 18 | sd.setDaemon(true); 19 | 20 | sd.start(); 21 | 22 | //设置主线程运行2s后结束 23 | try { 24 | Thread.sleep(200); 25 | } catch (InterruptedException e) { 26 | e.printStackTrace(); 27 | } 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src10/thread/ThreadPoolDemo.java: -------------------------------------------------------------------------------- 1 | package thread; 2 | 3 | import java.util.concurrent.*; 4 | import java.util.concurrent.atomic.*; 5 | import java.io.*; 6 | 7 | public class ThreadPoolDemo { 8 | public static void main(String[] args) throws InterruptedException, IOException { 9 | int corePoolSize = 2; //核心线程数 10 | int maximumPoolSize = 4; //最大线程数 11 | long keepAliveTime = 10; //线程消亡维持时间 12 | TimeUnit unit = TimeUnit.SECONDS; 13 | BlockingQueue workQueue = new ArrayBlockingQueue<>(2); //阻塞队列大小 14 | ThreadFactory threadFactory = new NameTreadFactory(); 15 | RejectedExecutionHandler handler = new MyIgnorePolicy(); 16 | ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, 17 | workQueue, threadFactory, handler); //参考ThreadPoolExecutor用法 18 | executor.prestartAllCoreThreads(); // 预启动所有核心线程 19 | 20 | for (int i = 1; i <= 10; i++) { 21 | MyTask task = new MyTask(String.valueOf(i)); 22 | executor.execute(task); 23 | } 24 | 25 | executor.shutdown(); 26 | 27 | // System.in.read(); //阻塞主线程 28 | } 29 | 30 | static class NameTreadFactory implements ThreadFactory { 31 | 32 | private final AtomicInteger mThreadNum = new AtomicInteger(1); 33 | 34 | @Override 35 | public Thread newThread(Runnable r) { 36 | Thread t = new Thread(r, "my-thread-" + mThreadNum.getAndIncrement()); //getAndIncrement方便加1操作 37 | System.out.println(t.getName() + " has been created"); 38 | return t; 39 | } 40 | } 41 | 42 | public static class MyIgnorePolicy implements RejectedExecutionHandler { 43 | 44 | public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { 45 | doLog(r, e); 46 | } 47 | 48 | private void doLog(Runnable r, ThreadPoolExecutor e) { 49 | // 可做日志记录等 50 | System.err.println( r.toString() + " rejected"); 51 | // System.out.println("completedTaskCount: " + e.getCompletedTaskCount()); 52 | } 53 | } 54 | 55 | static class MyTask implements Runnable { 56 | private String name; 57 | 58 | public MyTask(String name) { 59 | this.name = name; 60 | } 61 | 62 | @Override 63 | public void run() { 64 | try { 65 | System.out.println(this.toString() + " is running!"); 66 | Thread.sleep(300); //让任务执行慢点 67 | } catch (InterruptedException e) { 68 | e.printStackTrace(); 69 | } 70 | } 71 | 72 | public String getName() { 73 | return name; 74 | } 75 | 76 | @Override 77 | public String toString() { 78 | return "MyTask [name=" + name + "]"; 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src11/Generic/Durian.java: -------------------------------------------------------------------------------- 1 | package src11.Generic; 2 | 3 | public class Durian { 4 | // 使用T类型形参定义实例属性 5 | private T info; 6 | 7 | // 下面方法中使用T类型形参来定义构造函数 8 | public Durian(T info) { this.info = info; } 9 | public void setInfo(T info) { this.info = info;} 10 | public T getInfo() { return this.info;} 11 | 12 | // 静态泛型方法应该使用其他类型区分:里面的<>一定要紧跟静态声明 13 | public static Durianreadyear(K info) { 14 | return new Durian(info); 15 | } 16 | 17 | // public static Durian readyear(T info) { 18 | // return new Durian(info); 19 | // } 20 | } 21 | -------------------------------------------------------------------------------- /src11/Generic/GenericDurian.java: -------------------------------------------------------------------------------- 1 | package src11.Generic; 2 | 3 | public class GenericDurian { 4 | public static void main(String[] args) { 5 | // 由于传给T形参的是String,所以构造器参数只能是String 6 | Durian a1 = new Durian<>("猫山王"); 7 | System.out.println(a1.getInfo()); 8 | 9 | // 由于传给T形参的是Double,所以构造器参数只能是Double 10 | Durian a2 = new Durian<>(1.23); 11 | System.out.println(a2.getInfo()); 12 | 13 | // 调用静态方法 14 | Durian a3 = Durian.readyear(2022); 15 | System.out.println(a3.getInfo()); 16 | } 17 | } -------------------------------------------------------------------------------- /src11/Generic/GenericMethod.java: -------------------------------------------------------------------------------- 1 | package src11.Generic; 2 | 3 | public class GenericMethod { 4 | public void sampleMethod(T[] array) { 5 | for(int i=0; i list = new ArrayList<>(); 14 | list.add("str"); 15 | // list.add(100); //报错 16 | String name = list.get(0); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src11/Generic/GeneticStaticMethod.java: -------------------------------------------------------------------------------- 1 | package src11.Generic; 2 | 3 | public class GeneticStaticMethod { 4 | private K k; 5 | public GeneticStaticMethod(K k){ 6 | this.k=k; 7 | } 8 | public static GeneticStaticMethod fun1(K k){ 9 | //public static GeneticStaticMethod fun1(K k){ 10 | return new GeneticStaticMethod(k); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src11/Generic/ShowInterface.java: -------------------------------------------------------------------------------- 1 | package src11.Generic; 2 | 3 | public interface ShowInterface { 4 | public void show(T t); 5 | } 6 | 7 | //实现类已确定类型 8 | class ShowClass1 implements ShowInterface{ 9 | public void show(String t){ 10 | System.out.println("show:"+t); 11 | } 12 | } 13 | 14 | //实现类未确定类型 15 | class ShowClass2 implements ShowInterface{ 16 | public void show(T t){ 17 | System.out.println("show:"+t); 18 | } 19 | } -------------------------------------------------------------------------------- /src11/Generic/ShowInterfaceTest.java: -------------------------------------------------------------------------------- 1 | package src11.Generic; 2 | 3 | public class ShowInterfaceTest { 4 | public static void main(String[] args) { 5 | //实现类已确定类型 6 | ShowClass1 obj = new ShowClass1(); 7 | obj.show("java"); // test "java" to 7 8 | 9 | //实现类未确定类型,使用时确定 10 | ShowClass2 Obj = new ShowClass2<>(); 11 | Obj.show(7); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src11/Generic/WildCardDemo.java: -------------------------------------------------------------------------------- 1 | package Generic; 2 | import java.util.ArrayList; 3 | 4 | public class WildCardDemo { 5 | public static void printAllObject(ArrayList list) { 6 | for (Object object : list) { 7 | System.out.println(object); 8 | } 9 | } 10 | public static void main(String[] args) { 11 | ArrayList list1 = new ArrayList<>(); 12 | list1.add("java"); 13 | printAllObject(list1); 14 | 15 | ArrayList list2 = new ArrayList<>(); 16 | list2.add(7); 17 | printAllObject(list2); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src11/Reflect/ConTest.java: -------------------------------------------------------------------------------- 1 | package src11.Reflect; 2 | import java.lang.reflect.InvocationTargetException; 3 | import java.lang.reflect.Constructor; 4 | 5 | public class ConTest { 6 | public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { 7 | Student Harry = new Student("Harry Potter", 11); 8 | Class StudentClass = Harry.getClass(); 9 | Constructor con = StudentClass.getConstructor(String.class, int.class); 10 | Student Ron = (Student)con.newInstance("Ron Weasley", 11); 11 | System.out.println(Ron); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src11/Reflect/FieldTest.java: -------------------------------------------------------------------------------- 1 | package src11.Reflect; 2 | import java.lang.reflect.Field; 3 | 4 | public class FieldTest { 5 | public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { 6 | Student Harry = new Student("Harry Potter", 11); 7 | Class StudentClass = Harry.getClass(); 8 | Field f = StudentClass.getDeclaredField("name"); 9 | f.setAccessible(true); 10 | Object v1 = f.get(Harry); 11 | System.out.println(v1); 12 | f.set(Harry,"The boy who lived"); 13 | System.out.println(Harry.getName()); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src11/Reflect/MethodTest.java: -------------------------------------------------------------------------------- 1 | package src11.Reflect; 2 | 3 | import java.lang.reflect.InvocationTargetException; 4 | import java.lang.reflect.Method; 5 | 6 | public class MethodTest { 7 | public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { 8 | Student Harry = new Student("Harry Potter", 11); 9 | Method m = Student.class.getMethod("getName"); 10 | String n = (String) m.invoke(Harry); 11 | System.out.println(n); 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /src11/Reflect/Singleton.java: -------------------------------------------------------------------------------- 1 | package Reflect; 2 | public class Singleton { 3 | private static Singleton singleton = new Singleton(); 4 | private Singleton(){ 5 | // if(singleton != null) { 6 | // throw new RuntimeException("单例构造器禁止通过反射调用"); 7 | // } 8 | } 9 | public static Singleton getInstance(){ 10 | return singleton; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src11/Reflect/SingletonTest.java: -------------------------------------------------------------------------------- 1 | package Reflect; 2 | 3 | import java.lang.reflect.Constructor; 4 | import java.lang.reflect.InvocationTargetException; 5 | 6 | public class SingletonTest { 7 | public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { 8 | Class objectClass = Singleton.class; 9 | Constructor constructor = objectClass.getDeclaredConstructor(); 10 | constructor.setAccessible(true); 11 | Singleton instance = Singleton.getInstance(); 12 | Singleton newInstance = (Singleton)constructor.newInstance(); 13 | System.out.println(instance == newInstance); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src11/Reflect/Student.java: -------------------------------------------------------------------------------- 1 | package src11.Reflect; 2 | 3 | public class Student { 4 | private String name; 5 | private int age; 6 | 7 | public Student(String name, int age) { 8 | this.name = name; 9 | this.age = age; 10 | } 11 | public String getName(){ 12 | return name; 13 | } 14 | public void setName(String name){ 15 | this.name = name; 16 | } 17 | 18 | 19 | @Override 20 | public String toString() { 21 | return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; 22 | } 23 | } -------------------------------------------------------------------------------- /src11/Reflect/Test.java: -------------------------------------------------------------------------------- 1 | package Reflect; 2 | 3 | import java.util.Date; // 先有类 4 | 5 | public class Test { 6 | public static void main(String[] args) { 7 | Date date = new Date(); // 后有对象 8 | System.out.println(date); 9 | System.out.println(date.getClass());//反射 10 | System.out.println(date.getClass() == date.getClass()); // true 每个类只有一个Class对象 11 | } 12 | } -------------------------------------------------------------------------------- /src11/Reflect/forNameTest.java: -------------------------------------------------------------------------------- 1 | package Reflect; 2 | import java.util.Random; 3 | public class forNameTest { 4 | public static void main(String[] args) throws ClassNotFoundException { 5 | String className = "java.util.Random"; 6 | Class cl1 = Class.forName(className); //Class.forName 7 | System.out.println(cl1); 8 | Class cl2 = Random.class; //T.class 9 | // Class cl2 = int.class; //T.class 10 | System.out.println(cl2); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src11/Reflect/getClassTest.java: -------------------------------------------------------------------------------- 1 | package src11.Reflect; 2 | public class getClassTest { 3 | public static void main(String[] args) { 4 | Student Harry = new Student("Harry",11); // 5 | System.out.println(Harry.getClass());//获得类 6 | System.out.println(Harry.getClass().getName());//获得类名 7 | } 8 | } -------------------------------------------------------------------------------- /src11/TemplateMethod/Client.java: -------------------------------------------------------------------------------- 1 | package src11.TemplateMethod; 2 | 3 | public class Client { 4 | 5 | public static void main(String[] args) { 6 | System.out.println("----制作红豆豆浆----"); 7 | SoyMilk RedBeanSoyMilk = new RedBeanSoyMilk(); 8 | RedBeanSoyMilk.make(); 9 | 10 | System.out.println("----制作纯豆浆----"); 11 | SoyMilk PureSoyMilk = new PureSoyMilk(); 12 | PureSoyMilk.make(); 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /src11/TemplateMethod/PureSoyMilk.java: -------------------------------------------------------------------------------- 1 | package src11.TemplateMethod; 2 | 3 | public class PureSoyMilk extends SoyMilk{ 4 | 5 | @Override 6 | void addCondiments() { 7 | //空实现 8 | } 9 | 10 | @Override 11 | boolean customerWantCondiments() { 12 | return false; 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /src11/TemplateMethod/RedBeanSoyMilk.java: -------------------------------------------------------------------------------- 1 | package src11.TemplateMethod; 2 | 3 | public class RedBeanSoyMilk extends SoyMilk { 4 | 5 | @Override 6 | void addCondiments() { 7 | System.out.println("第二步:加入上好的红豆 "); 8 | } 9 | 10 | } -------------------------------------------------------------------------------- /src11/TemplateMethod/SoyMilk.java: -------------------------------------------------------------------------------- 1 | package src11.TemplateMethod; 2 | 3 | public abstract class SoyMilk { 4 | 5 | //模板方法, make, 模板方法可以做成final , 不让子类去覆盖. 6 | final void make() { 7 | select(); 8 | /*我们加入了一个条件语句,而该条件是否成立, 9 | 是有一个具体的方法决定的(customerWantCondiments(), 10 | 如果是需要加料的豆浆,才调用addCondiments())*/ 11 | if(customerWantCondiments()) { 12 | addCondiments(); 13 | } 14 | soak();//浸泡 15 | beat();//搅拌 16 | 17 | } 18 | 19 | //选材料 20 | void select() { 21 | System.out.println("第一步:选择好的新鲜黄豆"); 22 | } 23 | 24 | //添加不同的配料, 抽象方法, 子类具体实现 25 | abstract void addCondiments(); 26 | 27 | //浸泡 28 | void soak() { 29 | System.out.println("第三步:黄豆和配料开始浸泡,需要3小时"); 30 | } 31 | 32 | void beat() { 33 | System.out.println("第四步:黄豆和配料放到豆浆机去打碎"); 34 | } 35 | 36 | //钩子方法,决定是否需要添加配料 37 | boolean customerWantCondiments() { 38 | return true; 39 | } 40 | } -------------------------------------------------------------------------------- /src12/SocketTest/Client.java: -------------------------------------------------------------------------------- 1 | package src12.SocketTest; 2 | 3 | import java.io.*; 4 | import java.net.*; 5 | 6 | public class Client { 7 | public static void main(String[] args) { 8 | BufferedReader br = null; 9 | String clientStr=""; 10 | try { 11 | //建立通信端口,并向服务器端发送通信请求 12 | Socket s = new Socket("127.0.0.1",3838); 13 | System.out.println("与服务器端建立连接"); 14 | Send send = new Send(s); 15 | Thread t1 = new Thread(send); 16 | t1.start(); 17 | while(true){ 18 | 19 | //获取客户端通信的信息 20 | br = new BufferedReader(new InputStreamReader(s.getInputStream())); 21 | clientStr = br.readLine(); 22 | System.out.println("服务器端说:"+clientStr); 23 | } 24 | 25 | } catch (UnknownHostException e) { 26 | // TODO Auto-generated catch block 27 | e.printStackTrace(); 28 | } catch (IOException e) { 29 | // TODO Auto-generated catch block 30 | e.printStackTrace(); 31 | } 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src12/SocketTest/Send.java: -------------------------------------------------------------------------------- 1 | package src12.SocketTest; 2 | 3 | import java.io.*; 4 | import java.net.*; 5 | import java.util.*; 6 | 7 | 8 | public class Send implements Runnable{ 9 | Socket s ; 10 | Scanner in = new Scanner(System.in); 11 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 12 | public Send(Socket s){ 13 | this.s = s; 14 | } 15 | public void run() { 16 | // TODO Auto-generated method stub 17 | PrintWriter out = null; 18 | try { 19 | while(true){ 20 | out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()),true); 21 | String str = in.nextLine(); 22 | //br.readLine(); 23 | out.println(str); 24 | 25 | } 26 | 27 | } catch (Exception e) { 28 | // TODO Auto-generated catch block 29 | e.printStackTrace(); 30 | }finally{ 31 | out.close(); 32 | } 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src12/SocketTest/Server.java: -------------------------------------------------------------------------------- 1 | package src12.SocketTest; 2 | 3 | import java.io.*; 4 | import java.net.*; 5 | 6 | public class Server { 7 | public static void main(String[] args) { 8 | BufferedReader br = null; 9 | String clientStr=""; 10 | try { 11 | //创建一个监听的端口 12 | ServerSocket ss = new ServerSocket(3838); 13 | Socket s = null; 14 | System.out.println("服务器启动..."); 15 | //接受客户端通信请求,并建立专用通信端口 16 | s = ss.accept(); 17 | System.out.println("有客户端发送请求"); 18 | Send send = new Send(s); 19 | Thread t1 = new Thread(send); 20 | t1.start(); 21 | while(true){ 22 | //获取客户端通信的信息 23 | br = new BufferedReader(new InputStreamReader(s.getInputStream())); 24 | clientStr = br.readLine(); 25 | System.out.println("客户端:"+clientStr); 26 | } 27 | } catch (IOException e) { 28 | e.printStackTrace(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src12/observerTest/Cat.java: -------------------------------------------------------------------------------- 1 | package src12.observerTest; 2 | 3 | public class Cat extends MySubject{ 4 | @Override 5 | public void cry() { 6 | System.out.println("猫叫!"); 7 | System.out.println("-------"); 8 | //通知observer反馈 9 | for(Object obs:observers) { 10 | ((MyObserver) obs).response(); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src12/observerTest/Client.java: -------------------------------------------------------------------------------- 1 | package src12.observerTest; 2 | 3 | public class Client { 4 | public static void main(String[] args) { 5 | MySubject subject=new Cat(); 6 | MyObserver obs1,obs2,obs3; 7 | obs1=new Mouse(); 8 | obs2=new Mouse(); 9 | obs3=new Dog(); 10 | subject.attach(obs1); 11 | subject.attach(obs2); 12 | subject.attach(obs3); 13 | subject.cry(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src12/observerTest/Dog.java: -------------------------------------------------------------------------------- 1 | package src12.observerTest; 2 | 3 | public class Dog implements MyObserver{ 4 | @Override 5 | public void response() { 6 | System.out.println("狗跟着叫!"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src12/observerTest/Mouse.java: -------------------------------------------------------------------------------- 1 | package src12.observerTest; 2 | 3 | public class Mouse implements MyObserver{ 4 | @Override 5 | public void response() { 6 | System.out.println("老鼠努力逃跑!"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src12/observerTest/MyObserver.java: -------------------------------------------------------------------------------- 1 | package src12.observerTest; 2 | 3 | //抽象观察者类 4 | public interface MyObserver { 5 | void response(); //抽象响应方法 6 | } 7 | -------------------------------------------------------------------------------- /src12/observerTest/MySubject.java: -------------------------------------------------------------------------------- 1 | package src12.observerTest; 2 | 3 | import java.util.*; 4 | 5 | //抽象目标类 6 | public abstract class MySubject { 7 | //建立一个观察者的集合 8 | protected ArrayList observers = new ArrayList(); 9 | //注册方法 10 | public void attach(MyObserver observer) 11 | { 12 | observers.add(observer); 13 | } 14 | //注销方法 15 | public void detach(MyObserver observer) 16 | { 17 | observers.remove(observer); 18 | } 19 | public abstract void cry(); //抽象通知方法 20 | } 21 | -------------------------------------------------------------------------------- /src12/urlTest/URLDemo.java: -------------------------------------------------------------------------------- 1 | package urlTest; 2 | import java.net.*; 3 | import java.io.*; 4 | 5 | public class URLDemo { 6 | public static void main(String[] args) throws IOException { 7 | URL url=new URL("https://www.baidu.com/"); 8 | BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream())); 9 | BufferedWriter writer=new BufferedWriter(new FileWriter("info.html")); 10 | String line; 11 | while((line = reader.readLine()) != null){ 12 | System.out.println(line); 13 | writer.write(line); 14 | writer.newLine(); 15 | } 16 | reader.close(); 17 | writer.close(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src12/urlTest/UrlSite.java: -------------------------------------------------------------------------------- 1 | package urlTest; 2 | import java.net.*; 3 | import java.io.*; 4 | 5 | public class UrlSite { 6 | public static void main(String[] args) { 7 | if (args.length < 1) { 8 | System.out.println("没有给出URL"); 9 | System.exit(1); 10 | } else { 11 | for (int i = 0; i < args.length; i++) { 12 | urlSite(args[i]); 13 | } 14 | } 15 | 16 | } 17 | 18 | public static void urlSite(String urlname) { 19 | String s; 20 | URL url = null; 21 | InputStream urlstream=null; 22 | try{ 23 | url=new URL(urlname); 24 | } 25 | catch(Exception e){ 26 | System.out.println("url名字错误"); 27 | } 28 | try{ 29 | urlstream=url.openStream(); 30 | DataInputStream dat=new DataInputStream(urlstream); 31 | while(dat.readLine()!=null){ 32 | System.out.println(dat.readLine()); 33 | } 34 | } 35 | catch(IOException e){ 36 | System.out.println("URL文件打开错误"); 37 | } 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /src3/ArrayTest.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class ArrayTest { 4 | public static void main(String[] args) { 5 | //数组的定义和初始化,赋值 6 | int [] ns; 7 | ns =new int[]{1,2,3,4,5,6,7}; 8 | System.out.println("修改前数组长度:"+ns.length);//修改前数组长度:7 9 | 10 | ns=new int[]{8,9,10}; 11 | System.out.println("修改后的数组长度"+ns.length);//修改后的数组长度:3 12 | 13 | //---------------------------------------------- 14 | //思考打印值(看PPT) 15 | String[] names={"HIT","SZ","C++"}; 16 | String s=names[2]; 17 | names[2]="JAVA"; 18 | System.out.println(s);//C++ 19 | 20 | //---------------------------------------------- 21 | //forecah使用 22 | int[] ns2={1,4,9,16,25}; 23 | for(int i=0;i 100){ 14 | throw new MyException("你的优秀已经溢出了!"); 15 | }else{ 16 | System.out.println("你的成绩为:"+score); 17 | } 18 | }catch (InputMismatchException e1){ 19 | System.out.println("输入的成绩不是数字!"); 20 | }catch (MyException e2){ 21 | System.out.println(e2.getMessage()); 22 | } 23 | } 24 | //这个代码已经在src中写过了 25 | //关于exception的使用,是一种将异常集中管理的思想 26 | //如果不使用这样的作法,就会出现以下代码模式 27 | // if(exception1){ 28 | // ... 29 | // ... 30 | // }else{ 31 | // if(exception2){ 32 | // ... 33 | // ... 34 | // }else{ 35 | // if(exception3){ 36 | // ... 37 | // ... 38 | // }else{ 39 | // ... 40 | // ... 41 | // } 42 | // } 43 | // } 44 | //这样的代码模式使得代码不好管理 45 | } 46 | -------------------------------------------------------------------------------- /src4/inhent/Person.java: -------------------------------------------------------------------------------- 1 | public class Person { 2 | private String name; 3 | private int age; 4 | 5 | public Person(){ 6 | 7 | }//无参构造,因为已经有一个构造了,不加的话不会被编译器自动添加,为了防止遗忘,先加上 8 | 9 | public Person(String name,int age){ 10 | this.name=name; 11 | this.age=age; 12 | } 13 | 14 | public String getName(){ 15 | return name; 16 | } 17 | public void setName(String name,int age){ 18 | this.name=name; 19 | } 20 | 21 | public int getAge(){ 22 | return age; 23 | } 24 | 25 | public void setAge(int age){ 26 | this.age=age; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src4/inhent/PolymorphismTest.java: -------------------------------------------------------------------------------- 1 | //继承的多态性测试 2 | public class PolymorphismTest { 3 | public static void getInformation(Person p){ 4 | System.out.println("这个人名字是:"+p.getName()); 5 | System.out.println("这个人年龄是:"+p.getAge()); 6 | } 7 | 8 | public static void main(String[] args) { 9 | Person p1=new Student("小红",13,"hit"); 10 | Person p2=new Teacher("小绿",81,"thu"); 11 | getInformation(p1); 12 | getInformation(p2); 13 | } 14 | //这个人名字是:小红 15 | //这个人年龄是:13 16 | //这个人名字是:小绿 17 | //这个人年龄是:81 18 | 19 | //----------------------------------- 20 | //具有多态性 21 | } 22 | -------------------------------------------------------------------------------- /src4/inhent/Student.java: -------------------------------------------------------------------------------- 1 | public class Student extends Person{ 2 | 3 | //super(name,age)//ppt写错了 4 | private String school; 5 | 6 | 7 | public Student(){ 8 | 9 | } 10 | 11 | public Student(String name,int age,String school){ 12 | super(name,age); 13 | this.school=school; 14 | } 15 | 16 | public String getSchool(){ 17 | return this.school; 18 | } 19 | 20 | public static void main(String[] args) { 21 | //System.out.println(Student.name);//error 22 | Student stu=new Student("小明",12,"小学"); 23 | System.out.println("这个学生是:"+stu.getName());//这个学生是:小明 24 | System.out.println("这个学生年龄是:"+stu.getAge()+"岁");//这个学生年龄是:12岁 25 | System.out.println("这个学生读的是:"+stu.getSchool());//这个学生读的是:小学 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src4/inhent/Teacher.java: -------------------------------------------------------------------------------- 1 | public class Teacher extends Person{ 2 | private String office; 3 | 4 | public Teacher(){ 5 | 6 | } 7 | 8 | public Teacher(String name,int age,String office){ 9 | super(name,age); 10 | this.office=office; 11 | } 12 | 13 | public String getOffice(){ 14 | return office; 15 | } 16 | 17 | public static void main(String[] args) { 18 | Teacher tch=new Teacher("张老师",19,"衡水中学"); 19 | System.out.println("这个老师名字是:"+tch.getName());//这个老师名字是:张老师 20 | System.out.println("这个老师年龄是:"+tch.getAge()+"岁");//这个老师年龄是:19岁 21 | System.out.println("这个老师工作地点是:"+tch.getOffice());//这个老师工作地点是:衡水中学 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src4/innerClass/Father.java: -------------------------------------------------------------------------------- 1 | public class Father { 2 | //强壮指数 3 | public int strong(){ 4 | return 9; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src4/innerClass/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | Son s=new Son(); 4 | System.out.println("son's strong is:"+s.getStrong()); 5 | System.out.println("son's smart is:"+s.getSmart()); 6 | //son's strong is:10 7 | //son's smart is:9 8 | 9 | //可以通过内部类的方法实现(伪)多继承 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src4/innerClass/Mother.java: -------------------------------------------------------------------------------- 1 | public class Mother { 2 | //聪慧指数 3 | public int smart(){ 4 | return 8; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src4/innerClass/Son.java: -------------------------------------------------------------------------------- 1 | public class Son { 2 | 3 | //内部类继承Father类 4 | class Father_Inner extends Father{ 5 | public int strong(){ 6 | return super.strong()+1; 7 | } 8 | } 9 | 10 | //内部类继承Mother类 11 | class Mother_Inner extends Mother{ 12 | public int smart(){ 13 | return super.smart()+1; 14 | } 15 | } 16 | 17 | public int getStrong(){ 18 | return new Father_Inner().strong(); 19 | } 20 | 21 | public int getSmart(){ 22 | return new Mother_Inner().smart(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src4/innerClassByInterface/Daughter.java: -------------------------------------------------------------------------------- 1 | public interface Daughter extends Father,Mother{ 2 | void kind(); 3 | } 4 | //虽然类不能进行多继承 5 | //但是接口可以 6 | -------------------------------------------------------------------------------- /src4/innerClassByInterface/Father.java: -------------------------------------------------------------------------------- 1 | public interface Father { 2 | void strong(); 3 | } 4 | -------------------------------------------------------------------------------- /src4/innerClassByInterface/Girl.java: -------------------------------------------------------------------------------- 1 | public class Girl implements Daughter{ 2 | 3 | @Override 4 | public void kind() { 5 | System.out.println("She's very kind"); 6 | } 7 | 8 | @Override 9 | public void strong() { 10 | System.out.println("She's not strong"); 11 | } 12 | 13 | @Override 14 | public void smart() { 15 | System.out.println("She's very smart"); 16 | } 17 | 18 | public static void main(String[] args) { 19 | Girl g=new Girl();//由编译器自动添加 20 | g.kind(); 21 | g.strong(); 22 | g.smart(); 23 | } 24 | //She's very kind 25 | //She's not strong 26 | //She's very smart 27 | 28 | //由接口的多继承后实现 29 | } 30 | -------------------------------------------------------------------------------- /src4/innerClassByInterface/Mother.java: -------------------------------------------------------------------------------- 1 | public interface Mother { 2 | void smart(); 3 | } 4 | -------------------------------------------------------------------------------- /src4/interface/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void getDuty(Person p){ 3 | p.getDuty(); 4 | } 5 | 6 | public static void getMission(Person p){ 7 | p.getMission(); 8 | } 9 | 10 | public static void main(String[] args) { 11 | System.out.print("学生的职责是:"); 12 | getDuty(new Student()); 13 | //为了方便所以使用了匿名类 14 | System.out.print("老师的职责是:"); 15 | getDuty(new Teacher()); 16 | 17 | System.out.print("学生的使命是:"); 18 | getMission(new Student()); 19 | System.out.print("老师的使命是:"); 20 | getMission(new Teacher()); 21 | } 22 | //学生的职责是:好好学习 23 | //老师的职责是:科研教学 24 | //学生的使命是:为中华之崛起而读书 25 | //老师的使命是:立德树人 26 | } 27 | -------------------------------------------------------------------------------- /src4/interface/Person.java: -------------------------------------------------------------------------------- 1 | public interface Person { 2 | 3 | // 这里所有的字段都是public final static 4 | int totalNumber=100;//如果不初始化是会报错的 5 | 6 | // 这里所有的方法都是public abstract 7 | // 任何实现这个接口的类都必须重写这两个方法 8 | void getDuty(); 9 | void getMission(); 10 | } 11 | -------------------------------------------------------------------------------- /src4/interface/Student.java: -------------------------------------------------------------------------------- 1 | public class Student implements Person{ 2 | 3 | private String name; 4 | private int age; 5 | 6 | @Override 7 | public void getDuty() { 8 | System.out.println("好好学习"); 9 | } 10 | 11 | @Override 12 | public void getMission() { 13 | System.out.println("为中华之崛起而读书"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src4/interface/Teacher.java: -------------------------------------------------------------------------------- 1 | public class Teacher implements Person{ 2 | 3 | private String name; 4 | private int age; 5 | 6 | @Override 7 | public void getDuty() { 8 | System.out.println("科研教学"); 9 | } 10 | 11 | @Override 12 | public void getMission() { 13 | System.out.println("立德树人"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src4/object/Student.java: -------------------------------------------------------------------------------- 1 | public class Student extends Object{ 2 | //事实上所有的类都继承自Object类 3 | //就算不写extends Obeject也是ok的 4 | private String name; 5 | private int age; 6 | 7 | public Student(){ 8 | 9 | } 10 | 11 | public Student(String name,int age){ 12 | this.name=name; 13 | this.age=age; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | 20 | public int getAge() { 21 | return age; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src4/object/TestObject.java: -------------------------------------------------------------------------------- 1 | public class TestObject { 2 | public static void main(String[] args) { 3 | Object obj=new Student("张三",19); 4 | Student stu=(Student) obj;//可以使用强制向上转型 5 | System.out.println("stu's name:"+stu.getName()); 6 | System.out.println("stu's age:"+stu.getAge()); 7 | System.out.println("--------------------------"); 8 | //stu's name:张三 9 | //stu's age:19 10 | 11 | //--------------------------------------------- 12 | //equal 13 | //创建两个对象 14 | Object student_1=new Student("Zhangsan",19); 15 | Object student_2=new Student("Lisi",18); 16 | 17 | //不同的对象,内存地址不同,不相等,返回false 18 | System.out.println(student_1.equals(student_2));//实际上这里只是比较了引用是否相等 19 | 20 | //对象引用,内存地址相同,相等,返回true 21 | Student student_3=(Student) student_1; 22 | System.out.println(student_1.equals(student_3)); 23 | //false 24 | //true 25 | } 26 | } -------------------------------------------------------------------------------- /src4/super/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | Student stu=new Student(); 4 | stu.display(); 5 | stu.displayTarget(); 6 | } 7 | //学生年龄是:17 8 | //身为人的目标:享受生活 9 | //身为学生的目标:功夫到家 10 | 11 | 12 | 13 | //打印了父类的年龄 14 | } 15 | -------------------------------------------------------------------------------- /src4/super/Person.java: -------------------------------------------------------------------------------- 1 | public class Person { 2 | String name; 3 | int age=17; 4 | 5 | public Person(){ 6 | 7 | } 8 | 9 | public Person(String name,int age){ 10 | this.name=name; 11 | this.age=age; 12 | } 13 | 14 | public void getTarget(){ 15 | System.out.println("享受生活"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src4/super/Student.java: -------------------------------------------------------------------------------- 1 | public class Student extends Person{ 2 | int age=18; 3 | 4 | public Student(){ 5 | 6 | } 7 | 8 | public Student(String name,int age){ 9 | super(name,age);//调用父类含有两个参数的构造方法 10 | } 11 | 12 | public void display(){ 13 | System.out.println("学生年龄是:"+super.age);//为了展示super访问字段的方法所以将age的访问权放大了变成了包访问劝 14 | } 15 | 16 | public void getTarget(){ 17 | System.out.println("功夫到家"); 18 | } 19 | 20 | public void displayTarget(){ 21 | System.out.print("身为人的目标:"); 22 | super.getTarget(); 23 | System.out.print("身为学生的目标:"); 24 | this.getTarget(); 25 | } 26 | } -------------------------------------------------------------------------------- /src5/abstractFactory/HuaweiFactory.java: -------------------------------------------------------------------------------- 1 | package abstractFactory; 2 | 3 | public class HuaweiFactory implements IProductFactory{ 4 | //因为这里只有两个产品,为了跟ppt的内容尽量匹配,就不再添加过多的产品量 5 | @Override 6 | public IPhoneProduct phoneProduct() { 7 | System.out.println("The Huawei factory produced a Huawei mobile phone,tql!"); 8 | return new HuaweiPhone(); 9 | } 10 | 11 | @Override 12 | public IRouterProduct routerProduct() { 13 | System.out.println("Huawei factory produced a Huawei router,666!"); 14 | return new HuaweiRouter(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src5/abstractFactory/HuaweiPhone.java: -------------------------------------------------------------------------------- 1 | package abstractFactory; 2 | 3 | public class HuaweiPhone implements IPhoneProduct{ 4 | @Override 5 | public void start() { 6 | System.out.println("HuaweiPhone start..."); 7 | } 8 | 9 | @Override 10 | public void shutdown() { 11 | System.out.println("HuaweiPhone shutdown...over"); 12 | } 13 | 14 | @Override 15 | public void callup() { 16 | System.out.println("weiweiwei,here is huawei"); 17 | } 18 | 19 | @Override 20 | public void sendSMS() { 21 | System.out.println("Huawei message service for you"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src5/abstractFactory/HuaweiRouter.java: -------------------------------------------------------------------------------- 1 | package abstractFactory; 2 | 3 | public class HuaweiRouter implements IRouterProduct{ 4 | @Override 5 | public void start() { 6 | System.out.println("HuaweiRouter start..."); 7 | } 8 | 9 | @Override 10 | public void shutdown() { 11 | System.out.println("HuaweiRouter shutdown...over"); 12 | } 13 | 14 | @Override 15 | public void openwifi() { 16 | System.out.println("Huawei WIFI is opened"); 17 | } 18 | 19 | @Override 20 | public void setting() { 21 | System.out.println("Huawei Router service for you"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src5/abstractFactory/IPhoneProduct.java: -------------------------------------------------------------------------------- 1 | package abstractFactory; 2 | 3 | //手机产品接口 4 | public interface IPhoneProduct { 5 | //开始 6 | void start(); 7 | 8 | //关机 9 | void shutdown(); 10 | 11 | //打电话 12 | void callup(); 13 | 14 | //发邮件 15 | void sendSMS(); 16 | } 17 | -------------------------------------------------------------------------------- /src5/abstractFactory/IProductFactory.java: -------------------------------------------------------------------------------- 1 | package abstractFactory; 2 | 3 | public interface IProductFactory { 4 | //生产手机 5 | IPhoneProduct phoneProduct(); 6 | 7 | //生产路由器 8 | IRouterProduct routerProduct(); 9 | 10 | static IProductFactory FactoryCreate(String str){ 11 | IProductFactory ip=null; 12 | if(str.equals("huawei")){ 13 | ip=new HuaweiFactory(); 14 | }else if(str.equals("xiaomi")){ 15 | ip=new XiaomiFactory(); 16 | } 17 | return ip; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src5/abstractFactory/IRouterProduct.java: -------------------------------------------------------------------------------- 1 | package abstractFactory; 2 | 3 | //路由器产品接口 4 | public interface IRouterProduct { 5 | //开机 6 | void start(); 7 | 8 | //关机 9 | void shutdown(); 10 | 11 | //打开WIFI 12 | void openwifi(); 13 | 14 | //设置 15 | void setting(); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src5/abstractFactory/TestFactoryMain.java: -------------------------------------------------------------------------------- 1 | package abstractFactory; 2 | 3 | public class TestFactoryMain { 4 | public static void main(String[] args) { 5 | //抽象工厂模式与工厂模式区别:https://blog.csdn.net/gwz_6903/article/details/80494262(推荐博文) 6 | //最大的不同在于可以拥有多个抽象产品类 7 | IProductFactory huaweiFactory=IProductFactory.FactoryCreate("huawei"); 8 | IProductFactory xiaomiFactory=IProductFactory.FactoryCreate("xiaomi"); 9 | 10 | IPhoneProduct huaweiPhone=huaweiFactory.phoneProduct(); 11 | huaweiPhone.start(); 12 | huaweiPhone.callup(); 13 | huaweiPhone.shutdown(); 14 | 15 | IRouterProduct xiaomiRouter=xiaomiFactory.routerProduct(); 16 | xiaomiRouter.openwifi(); 17 | xiaomiRouter.setting(); 18 | } 19 | //运行结果 20 | //The Huawei factory produced a Huawei mobile phone,tql! 21 | //HuaweiPhone start... 22 | //weiweiwei,here is huawei 23 | //HuaweiPhone shutdown...over 24 | //Xiaomi factory produced a Xiaomi router, good! 25 | //Xiaomi WIFI is opened 26 | //Xiaomi Router service for you 27 | } 28 | -------------------------------------------------------------------------------- /src5/abstractFactory/XiaomiFactory.java: -------------------------------------------------------------------------------- 1 | package abstractFactory; 2 | 3 | public class XiaomiFactory implements IProductFactory{ 4 | @Override 5 | public IPhoneProduct phoneProduct() { 6 | System.out.println("Xiaomi factory produced a Xiaomi mobile phone, Wuhu!"); 7 | return new XiaomiPhone(); 8 | } 9 | 10 | @Override 11 | public IRouterProduct routerProduct() { 12 | System.out.println("Xiaomi factory produced a Xiaomi router, good!"); 13 | return new XiaomiRounter(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src5/abstractFactory/XiaomiPhone.java: -------------------------------------------------------------------------------- 1 | package abstractFactory; 2 | 3 | public class XiaomiPhone implements IPhoneProduct{ 4 | 5 | @Override 6 | public void start() { 7 | System.out.println("xiaomiPhone start..."); 8 | } 9 | 10 | @Override 11 | public void shutdown() { 12 | System.out.println("xiaomiPhone shutdown...over"); 13 | } 14 | 15 | @Override 16 | public void callup() { 17 | System.out.println("mimimi,this is xiaomi"); 18 | } 19 | 20 | @Override 21 | public void sendSMS() { 22 | System.out.println("Xiaomi message service for you"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src5/abstractFactory/XiaomiRounter.java: -------------------------------------------------------------------------------- 1 | package abstractFactory; 2 | 3 | public class XiaomiRounter implements IRouterProduct{ 4 | @Override 5 | public void start() { 6 | System.out.println("XiaomiRouter start..."); 7 | } 8 | 9 | @Override 10 | public void shutdown() { 11 | System.out.println("XiaomiRouter shutdown...over"); 12 | } 13 | 14 | @Override 15 | public void openwifi() { 16 | System.out.println("Xiaomi WIFI is opened"); 17 | } 18 | 19 | @Override 20 | public void setting() { 21 | System.out.println("Xiaomi Router service for you"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src5/factory/CheesePizza.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | class CheesePizza extends Pizza{ 4 | public void prepare(){ 5 | System.out.println("Preparing cheese pizza"); 6 | } 7 | 8 | public void bake(){ 9 | System.out.println("Baking cheese pizza"); 10 | } 11 | 12 | public void cut(){ 13 | System.out.println("Cutting cheese pizza"); 14 | } 15 | 16 | public void box(){ 17 | System.out.println("Boxing cheese pizza"); 18 | } 19 | } -------------------------------------------------------------------------------- /src5/factory/ChicagoPizzaStore.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | public class ChicagoPizzaStore extends PizzaStore{ 4 | Pizza createPizza(String type){ 5 | Pizza pizza = null; 6 | 7 | if (type.equals("cheese")) 8 | pizza = new CheesePizza(); 9 | else if (type.equals("greek")) 10 | pizza = new GreekPizza(); 11 | else if (type.equals("veggie")) 12 | pizza = new VeggiePizza(); 13 | return pizza; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src5/factory/GreekPizza.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | 4 | class GreekPizza extends Pizza{ 5 | public void prepare(){ 6 | System.out.println("Preparing Greek pizza"); 7 | } 8 | 9 | public void bake(){ 10 | System.out.println("Baking Greek pizza"); 11 | } 12 | 13 | public void cut(){ 14 | System.out.println("Cutting Greek pizza"); 15 | } 16 | 17 | public void box(){ 18 | System.out.println("Boxing Greek pizza"); 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /src5/factory/NYPizzaStore.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | public class NYPizzaStore extends PizzaStore{ 4 | Pizza createPizza(String type){ 5 | Pizza pizza = null; 6 | 7 | if (type.equals("cheese")) 8 | pizza = new CheesePizza(); 9 | else if (type.equals("greek")) 10 | pizza = new GreekPizza(); 11 | else if (type.equals("pepperoni")) 12 | pizza = new PepperoniPizza(); 13 | return pizza; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src5/factory/PepperoniPizza.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | class PepperoniPizza extends Pizza{ 4 | public void prepare(){ 5 | System.out.println("Preparing pepperoni pizza"); 6 | } 7 | 8 | public void bake(){ 9 | System.out.println("Baking pepperoni pizza"); 10 | } 11 | 12 | public void cut(){ 13 | System.out.println("Cutting pepperoni pizza"); 14 | } 15 | 16 | public void box(){ 17 | System.out.println("Boxing pepperoni pizza"); 18 | } 19 | } -------------------------------------------------------------------------------- /src5/factory/Pizza.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | public abstract class Pizza { 4 | public abstract void prepare(); 5 | public abstract void bake(); 6 | public abstract void cut(); 7 | public abstract void box(); 8 | } 9 | -------------------------------------------------------------------------------- /src5/factory/PizzaStore.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | public abstract class PizzaStore { 4 | public Pizza orderPizza(String type){ 5 | Pizza pizza; 6 | pizza = createPizza(type); 7 | 8 | pizza.prepare(); 9 | pizza.bake(); 10 | pizza.cut(); 11 | pizza.box(); 12 | 13 | return pizza; 14 | } 15 | 16 | abstract Pizza createPizza(String type); //工厂方法 17 | } 18 | -------------------------------------------------------------------------------- /src5/factory/TestOrderPizza.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | public class TestOrderPizza { 4 | public static void main(String[] args) { 5 | PizzaStore nyps = new NYPizzaStore(); 6 | PizzaStore cgps = new ChicagoPizzaStore(); 7 | 8 | Pizza pizza = nyps.orderPizza("cheese"); 9 | System.out.println("The first pizza....\n"); 10 | 11 | pizza = cgps.orderPizza("veggie"); 12 | System.out.println("The second pizza...."); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src5/factory/VeggiePizza.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | public class VeggiePizza extends Pizza{ 4 | public void prepare(){ 5 | System.out.println("Preparing veggie pizza"); 6 | } 7 | 8 | public void bake(){ 9 | System.out.println("Baking veggie pizza"); 10 | } 11 | 12 | public void cut(){ 13 | System.out.println("Cutting veggie pizza"); 14 | } 15 | 16 | public void box(){ 17 | System.out.println("Boxing veggie pizza"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src5/simplefactory/CheesePizza.java: -------------------------------------------------------------------------------- 1 | package simplefactory; 2 | 3 | class CheesePizza extends Pizza{ 4 | public void prepare(){ 5 | System.out.println("Preparing cheese pizza"); 6 | } 7 | 8 | public void bake(){ 9 | System.out.println("Baking cheese pizza"); 10 | } 11 | 12 | public void cut(){ 13 | System.out.println("Cutting cheese pizza"); 14 | } 15 | 16 | public void box(){ 17 | System.out.println("Boxing cheese pizza"); 18 | } 19 | } -------------------------------------------------------------------------------- /src5/simplefactory/GreekPizza.java: -------------------------------------------------------------------------------- 1 | package simplefactory; 2 | 3 | class GreekPizza extends Pizza{ 4 | public void prepare(){ 5 | System.out.println("Preparing Greek pizza"); 6 | } 7 | 8 | public void bake(){ 9 | System.out.println("Baking Greek pizza"); 10 | } 11 | 12 | public void cut(){ 13 | System.out.println("Cutting Greek pizza"); 14 | } 15 | 16 | public void box(){ 17 | System.out.println("Boxing Greek pizza"); 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /src5/simplefactory/PepperoniPizza.java: -------------------------------------------------------------------------------- 1 | package simplefactory; 2 | 3 | class PepperoniPizza extends Pizza{ 4 | public void prepare(){ 5 | System.out.println("Preparing pepperoni pizza"); 6 | } 7 | 8 | public void bake(){ 9 | System.out.println("Baking pepperoni pizza"); 10 | } 11 | 12 | public void cut(){ 13 | System.out.println("Cutting pepperoni pizza"); 14 | } 15 | 16 | public void box(){ 17 | System.out.println("Boxing pepperoni pizza"); 18 | } 19 | } -------------------------------------------------------------------------------- /src5/simplefactory/Pizza.java: -------------------------------------------------------------------------------- 1 | package simplefactory; 2 | 3 | abstract class Pizza { 4 | public abstract void prepare(); 5 | public abstract void bake(); 6 | public abstract void cut(); 7 | public abstract void box(); 8 | } -------------------------------------------------------------------------------- /src5/simplefactory/PizzaStore.java: -------------------------------------------------------------------------------- 1 | package simplefactory; 2 | 3 | public class PizzaStore { 4 | // SimplePizzaFactory simplefactory; 5 | // 6 | // public PizzaStore(SimplePizzaFactory simplefactory){ 7 | // this.simplefactory = simplefactory; 8 | // } 9 | 10 | //简单工厂模式,PizzaStore指向了简单工厂 11 | // public static Pizza orderPizza(String type){ 12 | // Pizza pizza; 13 | // 14 | // pizza = SimplePizzaFactory.createPizza(type); 15 | // 16 | // pizza.prepare(); 17 | // pizza.bake(); 18 | // pizza.cut(); 19 | // pizza.box(); 20 | // 21 | // return pizza; 22 | // } 23 | 24 | // 原始的pizzastore设计 25 | public static Pizza orderPizza(String type){ 26 | Pizza pizza; 27 | 28 | if (type.equals("cheese")) 29 | pizza = new CheesePizza(); 30 | else if (type.equals("greek")) 31 | pizza = new GreekPizza(); 32 | else if (type.equals("pepperoni")) 33 | pizza = new PepperoniPizza(); 34 | else 35 | pizza = null; 36 | 37 | pizza.prepare(); 38 | pizza.bake(); 39 | pizza.cut(); 40 | pizza.box(); 41 | 42 | return pizza; 43 | } 44 | 45 | 46 | public static void main(String[] args){ 47 | PizzaStore.orderPizza("greek"); 48 | } 49 | } -------------------------------------------------------------------------------- /src5/simplefactory/SimplePizzaFactory.java: -------------------------------------------------------------------------------- 1 | package simplefactory; 2 | 3 | public class SimplePizzaFactory { 4 | public static Pizza createPizza(String type){ 5 | Pizza pizza = null; 6 | 7 | if (type.equals("cheese")) 8 | pizza = new CheesePizza(); 9 | else if (type.equals("greek")) 10 | pizza = new GreekPizza(); 11 | else if (type.equals("pepperoni")) 12 | pizza = new PepperoniPizza(); 13 | 14 | return pizza; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src5/singleton/SingletonPattern.java: -------------------------------------------------------------------------------- 1 | package singleton; 2 | 3 | public class SingletonPattern { 4 | public static void main(String[] args){ 5 | for (int i=0; i<5; i++) { 6 | new Thread(() -> {Singeton.getInstance();}).start(); 7 | } 8 | } 9 | } 10 | 11 | class Singeton{ 12 | //饿汉式 13 | // private static Singeton singleton = new Singeton(); 14 | // private Singeton(){ 15 | // System.out.println("hello"); 16 | // } //构造方法一定是私有的 17 | // 18 | // public static Singeton getInstance(){ 19 | // return singleton; 20 | // } 21 | 22 | //懒汉式 -- 同步锁 23 | private static Singeton singeton; 24 | private Singeton(){ 25 | System.out.println("hello"); 26 | } 27 | 28 | public synchronized static Singeton getInstance() { 29 | if (singeton == null) 30 | singeton = new Singeton(); 31 | return singeton; 32 | } 33 | 34 | //懒汉式 -- 双重检查锁 35 | // private static Singeton singeton; 36 | // private Singeton(){ 37 | // System.out.println("hello"); 38 | // } 39 | // 40 | // public static Singeton getInstance(){ 41 | // if(singeton == null) 42 | // synchronized (Singeton.class) { 43 | // if(singeton == null) 44 | // singeton = new Singeton(); 45 | // } 46 | // return singeton; 47 | // } 48 | } 49 | -------------------------------------------------------------------------------- /src6/example/ATM.java: -------------------------------------------------------------------------------- 1 | package example; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ATM { 6 | private int amount; 7 | private String carID; 8 | private String password; 9 | private int customerMoney; 10 | private boolean aliveCard=true; 11 | private Scanner input = new Scanner(System.in); 12 | 13 | 14 | public ATM(int amount, String carID, String password, int customerMoney) { 15 | this.amount = amount; 16 | this.carID = carID; 17 | this.password = password; 18 | this.customerMoney = customerMoney; 19 | } 20 | 21 | public void PrintMain(){ 22 | System.out.println("---------------------------------"); 23 | System.out.println(" WELCOME "); 24 | System.out.println("---------------------------------"); 25 | } 26 | 27 | private String CMD(String str){ 28 | System.out.print(str); 29 | return input.nextLine(); 30 | } 31 | 32 | public void work(){ 33 | while(true){ 34 | PrintMain(); 35 | String testCarID=CMD("here is an ATM,please input your CarID:"); 36 | if(!testCarID.equals(carID)){ 37 | System.out.println("sorry your cardId is wrong"); 38 | System.out.println(carID); 39 | continue; 40 | } 41 | int i=0; 42 | for(i=0;i<3;i++){ 43 | String testPassword=CMD("please input your password:"); 44 | if(testPassword.equals(password)){ 45 | String use=CMD("save money(1) or load money(0)?"); 46 | int money; 47 | if(use.equals("0")){ 48 | try{ 49 | money=Integer.parseInt(CMD("How much money?")); 50 | }catch (Exception e){ 51 | System.out.println("sorry your \"money\" is not money"); 52 | continue; 53 | } 54 | if(money>customerMoney){ 55 | System.out.println("sorry ATM has no so much money"); 56 | continue; 57 | } 58 | customerMoney-=money; 59 | amount-=money; 60 | System.out.println("now you have "+customerMoney+"¥"); 61 | System.out.println("now ATM have "+amount+"¥"); 62 | }else if(use.equals("1")){ 63 | try{ 64 | money=Integer.parseInt(CMD("How much money?")); 65 | }catch (Exception e){ 66 | System.out.println("sorry your \"money\" is not money"); 67 | continue; 68 | } 69 | customerMoney+=money; 70 | amount+=money; 71 | System.out.println("now you have "+customerMoney+"¥"); 72 | System.out.println("now ATM have "+amount+"¥"); 73 | }else{ 74 | System.out.println("sorry no this usage"); 75 | break; 76 | } 77 | break; 78 | } 79 | } 80 | if(i==3){ 81 | System.out.println("sorry You have entered the wrong password three times,now we can't service for you."); 82 | this.aliveCard=false; 83 | System.exit(0); 84 | } 85 | } 86 | } 87 | 88 | //注,这里的work是死循环如果不是连续输错三次密码是不会结束程序的 89 | public static void main(String[] args) { 90 | // ATM atm=new ATM(5000,"1234567812345678","12345",2000); 91 | // atm.work(); 92 | // ATM atm=new ATM(4000,"1234567812345678","12345",2000); 93 | // atm.work(); 94 | ATM atm=new ATM(4000,"1234567812345678","12345",1000); 95 | atm.work(); 96 | } 97 | //运行结果 98 | //--------------------------------- 99 | // WELCOME 100 | //--------------------------------- 101 | //here is an ATM,please input your CarID:1234567812345678 102 | //please input your password:12345 103 | //save money(1) or load money(0)?0 104 | //How much money?1000 105 | //now you have 1000¥ 106 | //now ATM have 4000¥ 107 | 108 | //--------------------------------- 109 | // WELCOME 110 | //--------------------------------- 111 | //here is an ATM,please input your CarID:123 112 | //sorry your cardId is wrong 113 | //1234567812345678 114 | 115 | //--------------------------------- 116 | // WELCOME 117 | //--------------------------------- 118 | //here is an ATM,please input your CarID:1234567812345678 119 | //please input your password:654321 120 | //please input your password:987654 121 | //please input your password:876543 122 | //sorry You have entered the wrong password three times,now we can't service for you. 123 | } -------------------------------------------------------------------------------- /src6/example/BlackBox.java: -------------------------------------------------------------------------------- 1 | package example; 2 | 3 | public class BlackBox { 4 | public boolean timeLimit(int time){ 5 | int mouth=time%100; 6 | return mouth<13 && mouth>=1 && time>=199001 && time<=202112; 7 | } 8 | 9 | public int Add(int x1,int x2){ 10 | return (1<=x1 && x1<=100 && 50<=x2 && x2<=200)? (x1+x2) : -1; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src6/example/WhiteBox.java: -------------------------------------------------------------------------------- 1 | package example; 2 | 3 | import java.io.*; 4 | 5 | public class WhiteBox { 6 | public int Funcl(int a,int b,int x){ 7 | if((a>1) && (b==0)){ 8 | x=x/a; 9 | System.out.println("p2"); 10 | }else{ 11 | System.out.println("p1"); 12 | } 13 | if((a==2)||(x>1)){ 14 | x=x+1; 15 | System.out.println("p4"); 16 | }else{ 17 | System.out.println("p3"); 18 | } 19 | return x; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src6/test/BlackBoxTest.java: -------------------------------------------------------------------------------- 1 | package test; 2 | 3 | import example.ATM; 4 | import example.BlackBox; 5 | import org.junit.jupiter.api.BeforeAll; 6 | import org.junit.jupiter.api.Test; 7 | 8 | import static org.junit.jupiter.api.Assertions.assertEquals; 9 | 10 | public class BlackBoxTest { 11 | static BlackBox blackbox; 12 | @BeforeAll 13 | static void begin(){ 14 | blackbox=new BlackBox(); 15 | } 16 | 17 | //等价类划分例子 18 | @Test 19 | public void testTimeLimit1(){ 20 | // assertEquals(true,blackbox.timeLimit(aaa123));//无效输入 21 | assertEquals(false,blackbox.timeLimit(2011));//有效的输入 22 | assertEquals(false,blackbox.timeLimit(20140408));//无效输入 23 | assertEquals(false,blackbox.timeLimit(187905));//无效输入 24 | assertEquals(false,blackbox.timeLimit(209811));//无效输入 25 | assertEquals(false,blackbox.timeLimit(200100));//无效输入 26 | assertEquals(false,blackbox.timeLimit(200156));//无效输入 27 | assertEquals(true,blackbox.timeLimit(201408));//有效输入 28 | } 29 | 30 | //边界值分析 31 | @Test 32 | public void testAdd(){ 33 | //穷尽测试 34 | ranctangleTest(0,201,101,201,0,49); 35 | } 36 | 37 | @Test 38 | public void testAdd2(){ 39 | //穷尽有限域测试 40 | ranctangleTest(1,200,100,200,1,50); 41 | } 42 | 43 | @Test 44 | public void testAdd3(){ 45 | //多边界测试 46 | ranctangleTest(0,201,2,201,0,199); 47 | ranctangleTest(99,201,101,201,99,199); 48 | ranctangleTest(0,51,2,51,0,49); 49 | ranctangleTest(99,51,101,51,99,49); 50 | } 51 | 52 | @Test 53 | public void testAdd4(){ 54 | //单边界测试 55 | ranctangleTest(0,199,2,199,0,51); 56 | ranctangleTest(2,201,99,201,2,199); 57 | ranctangleTest(99,199,101,199,99,51); 58 | ranctangleTest(2,51,99,51,2,49); 59 | } 60 | 61 | @Test 62 | public void testAdd5(){ 63 | //简单测试方法 64 | //上 65 | assertEquals(-1,blackbox.Add(55,201)); 66 | assertEquals((55+200),blackbox.Add(55,200)); 67 | assertEquals((55+199),blackbox.Add(55,199)); 68 | 69 | //右 70 | assertEquals((99+150),blackbox.Add(99,150)); 71 | assertEquals((100+150),blackbox.Add(100,150)); 72 | assertEquals(-1,blackbox.Add(101,150)); 73 | 74 | //下 75 | assertEquals((55+51),blackbox.Add(55,51)); 76 | assertEquals((55+50),blackbox.Add(55,50)); 77 | assertEquals(-1,blackbox.Add(55,49)); 78 | 79 | //左 80 | assertEquals((2+150),blackbox.Add(2,150)); 81 | assertEquals((1+150),blackbox.Add(1,150)); 82 | assertEquals(-1,blackbox.Add(0,150)); 83 | } 84 | 85 | private void ranctangleTest(int x1,int y1,int x2,int y2,int x3,int y3){ 86 | //这里如果有一个函数接口,就可以测试多种函数,为了简单起见,要求上面传入的参数是一个长方形的左上,右上,左下顶点坐标 87 | //实在算不出ppt给的边界,所以所有的边界宽度都取了1 88 | for(int i=x1;i100) && (j<50 || j>150)){ 91 | assertEquals(-1,blackbox.Add(i,j)); 92 | }else{ 93 | assertEquals((i+j),blackbox.Add(i,j)); 94 | } 95 | if(j>y1-1){ 96 | j+=96; 97 | } 98 | } 99 | } 100 | } 101 | 102 | //这里的Test也许是因为System.in没有办法被调用到,所以把测试放在ATM的main方法里面了 103 | // @Test 104 | // public void TestATM(){ 105 | // ATM atm=new ATM(4000,"12345","123",2000); 106 | // atm.work(); 107 | // } 108 | } -------------------------------------------------------------------------------- /src6/test/WhiteBoxTest.java: -------------------------------------------------------------------------------- 1 | package test; 2 | 3 | import example.WhiteBox; 4 | import org.junit.jupiter.api.BeforeAll; 5 | import org.junit.jupiter.api.Test; 6 | 7 | import static org.junit.jupiter.api.Assertions.assertEquals; 8 | 9 | public class WhiteBoxTest { 10 | //4个基本逻辑判断条件 11 | //T1:a>1 12 | //T2:b==0 13 | //T3:a==2 14 | //T4:x>1 15 | 16 | //4条执行路径 17 | //L13:p1->p3 18 | //L14:p1->p4 19 | //L23:p2->p3 20 | //L24:p2->p4 21 | 22 | private static WhiteBox whiteBox; 23 | 24 | @BeforeAll 25 | public static void gululu(){ 26 | whiteBox=new WhiteBox(); 27 | } 28 | //语句覆盖率=(至少被执行一次的语句数量)/(可执行的语句数量) 29 | 30 | 31 | //语句覆盖 32 | //至少执行程序中所有语句一次。 33 | @Test 34 | public void test1(){ 35 | assertEquals(3,whiteBox.Funcl(2,0,4));//覆盖路径:L24(只是完成一次程序执行) 36 | } 37 | 38 | //判定测试 39 | //也称为分支覆盖,至少执行程序中每个分支一次,保证程序中每个判定节点取得每 40 | //种可能的结果至少一次。 41 | @Test 42 | public void test2(){ 43 | assertEquals(3,whiteBox.Funcl(1,1,2));//覆盖路径:L14 44 | assertEquals(1,whiteBox.Funcl(3,0,3));//覆盖路径:L23 45 | } 46 | 47 | //条件覆盖 48 | //不仅每个语句至少执行一次,而且使判定表达式中的每个基本逻辑判定条件都 49 | //取到各种可能的结果(真、假) 50 | @Test 51 | public void test3(){ 52 | assertEquals(1,whiteBox.Funcl(2,1,0));//覆盖条件:T1=true;T2=false;T3=true;T4=false; 53 | assertEquals(3,whiteBox.Funcl(1,0,2));//覆盖条件:T1=false;T2=true;T3=false;T4=true; 54 | } 55 | 56 | //判定条件覆盖 57 | //同时满足判定覆盖和条件覆盖。 58 | @Test 59 | public void test4(){ 60 | assertEquals(3,whiteBox.Funcl(2,0,4));//覆盖条件:T1=true;T2=true;T3=true;T4=true;覆盖路径:L24 61 | assertEquals(1,whiteBox.Funcl(1,1,1));//覆盖条件:T1=false;T2=false;T3=false;T4=false;覆盖路径:L13 62 | } 63 | 64 | //条件组合覆盖 65 | //每一个if语句含两条条件式,共16种不同条件组合情况 66 | //保证程序每个判定节点中,所有简单判定条件的所有可能的取值组合情况至少 67 | //执行一次。 68 | @Test 69 | public void test6(){ 70 | assertEquals(3,whiteBox.Funcl(2,0,4));//使用T1,T2,T3,T4是否为真的顺序来注释(1为真0为假):1111 71 | assertEquals(2,whiteBox.Funcl(2,0,2));//1110 72 | assertEquals(3,whiteBox.Funcl(3,0,6));//1101 73 | assertEquals(1,whiteBox.Funcl(3,0,3));//1100 74 | assertEquals(3,whiteBox.Funcl(2,1,2));//1011 75 | assertEquals(2,whiteBox.Funcl(2,1,1));//1010 76 | assertEquals(3,whiteBox.Funcl(3,1,2));//1001 77 | assertEquals(3,whiteBox.Funcl(3,1,2));//1000 78 | assertEquals(3,whiteBox.Funcl(1,0,2));//0101 79 | assertEquals(1,whiteBox.Funcl(1,0,1));//0100 80 | assertEquals(3,whiteBox.Funcl(1,1,2));//0001 81 | assertEquals(1,whiteBox.Funcl(1,1,1));//0000 82 | } 83 | 84 | //路径覆盖 85 | //使程序中每一条可能的路径至少执行一次。 86 | @Test 87 | public void test7(){ 88 | assertEquals(3,whiteBox.Funcl(2,0,4));//L24 89 | assertEquals(1,whiteBox.Funcl(1,1,1));//L13 90 | assertEquals(3,whiteBox.Funcl(1,1,2));//L14 91 | assertEquals(1,whiteBox.Funcl(3,0,3));//L23 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src7/collection/ArraylistTest.java: -------------------------------------------------------------------------------- 1 | package collection; 2 | import java.util.*; 3 | 4 | public class ArraylistTest { 5 | public static void main(String[] args) { 6 | ArrayList sites = new ArrayList(); 7 | //增加元素 8 | sites.add("Google"); 9 | sites.add("Amazon"); 10 | sites.add("Taobao"); 11 | sites.add("Weibo"); 12 | sites.add(1,"Baidu"); 13 | System.out.println(sites); 14 | 15 | //删除元素 16 | sites.remove(3); 17 | sites.remove("Google"); 18 | System.out.println("After removal, " + sites); 19 | 20 | //查询元素 21 | System.out.println(sites.get(1)); 22 | 23 | //修改元素 24 | sites.set(1, "Jingdong"); 25 | System.out.println("After modification, " + sites); 26 | 27 | //遍历 28 | // for循环遍历 29 | for (int i=0; i sites = new HashMap<>(); //需指定key和value的类型 7 | //添加键值对 8 | sites.put(1, "Google"); 9 | sites.put(2, "Amazon"); 10 | sites.put(3, "Taobao"); 11 | sites.put(4, "Zhihu"); 12 | sites.put(4, "Yahoo"); //替换掉已有键的值 13 | System.out.println(sites); 14 | 15 | //查找键值对 16 | System.out.println(sites.get(3)); 17 | 18 | //删除键值对 19 | sites.remove("Yahoo"); 20 | // sites.clear(); 21 | 22 | //遍历键值对 23 | System.out.println("----------1. keySet()+增强for----------"); 24 | Set keyset = sites.keySet(); 25 | for (Integer key: keyset){ 26 | System.out.println(sites.get(key)); 27 | } 28 | 29 | System.out.println("----------2. 另一种形式----------"); 30 | for(Integer key: sites.keySet()){ 31 | System.out.println("key: " + key + " value: " + sites.get(key)); 32 | } 33 | 34 | System.out.println("----------3. values()+增强for----------"); 35 | for(String value: sites.values()){ 36 | System.out.println(value); 37 | } 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /src7/collection/HashsetTest.java: -------------------------------------------------------------------------------- 1 | package collection; 2 | import java.util.*; 3 | 4 | public class HashsetTest { 5 | public static void main(String[] args) { 6 | HashSet sites = new HashSet<>(); 7 | //添加元素,无序 8 | sites.add("Google"); 9 | sites.add("Amazon"); 10 | sites.add("Taobao"); 11 | sites.add("Weibo"); 12 | System.out.println(sites); 13 | 14 | //判断元素是否存在 15 | System.out.println(sites.contains("Weibo")); 16 | 17 | //删除元素 18 | sites.remove("Weibo"); 19 | // sites.clear(); 20 | 21 | //遍历(重点) 22 | System.out.println("----------1.遍历元素foreach----------"); 23 | for (String i: sites){ 24 | System.out.println(i); 25 | } 26 | 27 | System.out.println("----------2.迭代器遍历----------"); 28 | Iterator it = sites.iterator(); 29 | while (it.hasNext()){ 30 | System.out.println(it.next()); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src7/collection/LinkedlistTest.java: -------------------------------------------------------------------------------- 1 | package collection; 2 | import java.util.*; 3 | 4 | public class LinkedlistTest { 5 | public static void main(String[] args) { 6 | LinkedList sites = new LinkedList<>(); 7 | //增加元素 8 | sites.add("Google"); 9 | sites.add("Amazon"); 10 | sites.add("Taobao"); 11 | sites.add("Weibo"); 12 | sites.addFirst("Baidu"); 13 | sites.addLast("Tencent"); 14 | sites.add(0, "ByteDance"); 15 | System.out.println(sites); //有顺序,可重复 16 | 17 | //删除元素 18 | System.out.println("----------删除元素----------"); 19 | sites.remove("Baidu"); 20 | sites.remove(1); 21 | sites.removeFirst(); 22 | sites.removeLast(); 23 | 24 | //查询元素 25 | System.out.println("----------查询元素----------"); 26 | sites.get(1); 27 | sites.getFirst(); 28 | sites.getLast(); 29 | 30 | //遍历 31 | System.out.println("----------1.遍历元素for----------"); 32 | for(int i=0; i< sites.size(); i++){ 33 | System.out.println(sites.get(i)); 34 | } 35 | 36 | System.out.println("----------2.遍历元素foreach----------"); 37 | for (String i: sites){ 38 | System.out.println(i); 39 | } 40 | 41 | System.out.println("----------3.用迭代器遍历----------"); 42 | Iterator it = sites.iterator(); 43 | while(it.hasNext()){ 44 | System.out.println(it.next()); 45 | } 46 | 47 | System.out.println("----------4.用列表迭代器遍历----------"); 48 | ListIterator lit = sites.listIterator(); 49 | while(lit.hasNext()){ 50 | System.out.println(lit.next()); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src7/iteratorTest/Aggregate.java: -------------------------------------------------------------------------------- 1 | package iteratorTest; 2 | 3 | //Aggregate聚集抽象类 4 | public interface Aggregate { 5 | //添加 6 | void add(Object object); 7 | 8 | //创建迭代器 9 | Iterator createIterator(); 10 | } 11 | -------------------------------------------------------------------------------- /src7/iteratorTest/ConcreteAggregate.java: -------------------------------------------------------------------------------- 1 | package iteratorTest; 2 | import java.util.*; 3 | 4 | //ConcreteAggregate集体聚集类,继承Aggregate 5 | public class ConcreteAggregate implements Aggregate { 6 | private List items = new ArrayList<>(); 7 | 8 | @Override 9 | public Iterator createIterator() { 10 | return new ConcreteIterator(items); 11 | } 12 | 13 | public void add(Object object) { 14 | items.add(object); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src7/iteratorTest/ConcreteIterator.java: -------------------------------------------------------------------------------- 1 | package iteratorTest; 2 | import java.util.*; 3 | 4 | //ConcreteIterator具体迭代器类,实现Iterator 5 | public class ConcreteIterator implements Iterator { 6 | private List list; 7 | private int currentIndex = 0; 8 | 9 | public ConcreteIterator(List list) { 10 | this.list = list; 11 | } 12 | 13 | @Override 14 | public Object next() { 15 | if (hasNext()) { 16 | return list.get(currentIndex++); 17 | } 18 | return null; 19 | } 20 | 21 | @Override 22 | public boolean hasNext() { 23 | if (currentIndex == list.size()) { 24 | return false; 25 | } 26 | return true; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src7/iteratorTest/Iterator.java: -------------------------------------------------------------------------------- 1 | package iteratorTest; 2 | 3 | //Iterator迭代器接口类 4 | public interface Iterator { 5 | //两个重要的方法 6 | //得到下一个对象 7 | Object next(); 8 | 9 | //判断是否有下一个对象 10 | boolean hasNext(); 11 | } 12 | -------------------------------------------------------------------------------- /src7/iteratorTest/IteratorTest.java: -------------------------------------------------------------------------------- 1 | package iteratorTest; 2 | import java.util.*; 3 | 4 | public class IteratorTest { 5 | public static void main(String[] args) { 6 | // ArrayList numbers = new ArrayList<>(); 7 | // numbers.add(12); 8 | // numbers.add(8); 9 | // numbers.add(24); 10 | // 11 | // 12 | // Iterator it = numbers.iterator(); 13 | // while(it.hasNext()){ 14 | // Integer i = (Integer) it.next(); //强制类型转换 15 | // if (i < 10){ 16 | // it.remove(); 17 | // } 18 | // } 19 | // System.out.println(numbers); 20 | 21 | Aggregate aggregate = new ConcreteAggregate(); 22 | aggregate.add(1); 23 | aggregate.add(2); 24 | aggregate.add(3); 25 | aggregate.add(4); 26 | 27 | Iterator iterator = aggregate.createIterator(); 28 | while (iterator.hasNext()) { 29 | System.out.println(iterator.next()); 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src7/strategy/AdvancedMemberStrategy.java: -------------------------------------------------------------------------------- 1 | package strategy; 2 | 3 | public class AdvancedMemberStrategy implements MemberStrategy{ 4 | @Override 5 | public double calcPrice(double booksPrice) { 6 | System.out.println("对于高级会员的折扣为20%"); 7 | return booksPrice * 0.8; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src7/strategy/Client.java: -------------------------------------------------------------------------------- 1 | package strategy; 2 | 3 | public class Client { 4 | public static void main(String[] args) { 5 | //选择并创建需要使用的策略对象 6 | MemberStrategy strategy = new AdvancedMemberStrategy(); 7 | //创建环境 8 | Price price = new Price(strategy); 9 | //计算价格 10 | double quote = price.quote(300); 11 | System.out.println("图书的最终价格为:" + quote); } 12 | } 13 | -------------------------------------------------------------------------------- /src7/strategy/IntermediateMemberStrategy.java: -------------------------------------------------------------------------------- 1 | package strategy; 2 | 3 | public class IntermediateMemberStrategy implements MemberStrategy{ 4 | @Override 5 | public double calcPrice(double booksPrice) { 6 | System.out.println("对于中级会员的折扣为10%"); 7 | return booksPrice * 0.9; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src7/strategy/MemberStrategy.java: -------------------------------------------------------------------------------- 1 | package strategy; 2 | 3 | public interface MemberStrategy { 4 | /** 5 | * 计算图书的价格 6 | * @param booksPrice 图书的原价 7 | * @return 计算出打折后的价格 8 | */ 9 | public double calcPrice(double booksPrice); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src7/strategy/Price.java: -------------------------------------------------------------------------------- 1 | package strategy; 2 | 3 | public class Price { 4 | private MemberStrategy strategy; 5 | /** 6 | * 构造函数,传入一个具体的策略对象 7 | * @param strategy 具体的策略对象 8 | */ 9 | public Price(MemberStrategy strategy){ 10 | this.strategy = strategy; 11 | } 12 | /** 13 | *计算图书的价格 14 | * @param booksPrice 图书的原价 15 | * @return 计算出打折后的价格 16 | */ 17 | public double quote(double booksPrice){ 18 | return this.strategy.calcPrice(booksPrice); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src7/strategy/PrimaryMemberStrategy.java: -------------------------------------------------------------------------------- 1 | package strategy; 2 | 3 | public class PrimaryMemberStrategy implements MemberStrategy{ 4 | @Override 5 | public double calcPrice(double booksPrice) { 6 | System.out.println("对于初级会员的没有折扣"); 7 | return booksPrice; 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src8/DAO/DataAccessObjectPatternDemo.java: -------------------------------------------------------------------------------- 1 | package DAO; 2 | 3 | public class DataAccessObjectPatternDemo { 4 | public static void main(String[] args) { 5 | StudentDAO studentDao = new StudentDaoImpl(); 6 | //输出所有的学生   7 | for (Student student : studentDao.getAllStudents()) { 8 | System.out.println("Student: [RollNo : "+ student.getRollNo() + ", Name : " + student.getName() + " ]"); 9 | } 10 | System.out.println(); 11 | //更新学生   12 | Student student = studentDao.getAllStudents().get(0); 13 | student.setName("Michael"); 14 | studentDao.updateStudent(student); 15 | System.out.println(); 16 | //获取学生   17 | studentDao.getStudent(0); 18 | System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]"); 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src8/DAO/Student.java: -------------------------------------------------------------------------------- 1 | package DAO; 2 | 3 | public class Student { 4 | private String name; 5 | private int rollNo; 6 | 7 | Student(String name, int rollNo){ 8 | this.name = name; 9 | this.rollNo = rollNo; 10 | } 11 | 12 | public String getName(){ 13 | return name; 14 | } 15 | 16 | public void setName(String name){ 17 | this.name = name; 18 | } 19 | 20 | public int getRollNo(){ 21 | return rollNo; 22 | } 23 | 24 | public void setRollNo(int rollNo){ 25 | this.rollNo = rollNo; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src8/DAO/StudentDAO.java: -------------------------------------------------------------------------------- 1 | package DAO; 2 | 3 | import java.util.*; 4 | 5 | public interface StudentDAO { 6 | List getAllStudents(); 7 | Student getStudent(int rollNo); 8 | void updateStudent(Student student); 9 | void deleteStudent(Student student); 10 | } 11 | -------------------------------------------------------------------------------- /src8/DAO/StudentDaoImpl.java: -------------------------------------------------------------------------------- 1 | package DAO; 2 | 3 | import java.util.*; 4 | 5 | public class StudentDaoImpl implements StudentDAO { 6 | //列表是当作一个数据库   7 | List students; 8 | 9 | public StudentDaoImpl() { 10 | students = new ArrayList(); 11 | Student student1 = new Student("Robert", 0); 12 | Student student2 = new Student("John", 1); 13 | students.add(student1); 14 | students.add(student2); 15 | } 16 | 17 | @Override 18 | public List getAllStudents() { 19 | return students; 20 | } 21 | 22 | @Override 23 | public void deleteStudent(Student student) { 24 | students.remove(student.getRollNo()); 25 | System.out.println("Student: Roll No " + student.getRollNo() + ", deleted from database"); 26 | } 27 | 28 | @Override 29 | public Student getStudent(int rollNo) { 30 | return students.get(rollNo); 31 | } 32 | 33 | @Override 34 | public void updateStudent(Student student) { 35 | students.get(student.getRollNo()).setName(student.getName()); 36 | System.out.println("Student: Roll No " + student.getRollNo() 37 | + ", updated in the database"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src8/fileRW/BRRead.java: -------------------------------------------------------------------------------- 1 | package fileRW; 2 | import java.io.*; 3 | public class BRRead { 4 | public static void main(String[] args) throws IOException { 5 | char c; 6 | // 使用 System.in 创建 BufferedReader 7 | BufferedReader br = new BufferedReader(new 8 | InputStreamReader(System.in)); 9 | System.out.println("输入字符, 按下 'q' 键退出。"); 10 | // 读取字符 11 | do { 12 | c = (char) br.read(); 13 | System.out.println(c); 14 | } while (c != 'q'); 15 | } 16 | } -------------------------------------------------------------------------------- /src8/fileRW/BRReadLines.java: -------------------------------------------------------------------------------- 1 | package fileRW; 2 | //使用 BufferedReader 在控制台读取字符 3 | import java.io.*; 4 | public class BRReadLines { 5 | public static void main(String[] args) throws IOException { 6 | // 使用 System.in 创建 BufferedReader 7 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 8 | String str; 9 | System.out.println("Enter lines of text."); 10 | System.out.println("Enter 'end' to quit."); 11 | do { 12 | str = br.readLine(); 13 | System.out.println(str); 14 | } while (!str.equals("end")); 15 | } 16 | } -------------------------------------------------------------------------------- /src8/fileRW/ChartoByte.java: -------------------------------------------------------------------------------- 1 | package fileRW; 2 | import java.io.*; 3 | 4 | public class ChartoByte { 5 | public static void main(String[] args) { 6 | try { 7 | //构建输出流字节对象 8 | FileOutputStream fileOutputStream = new FileOutputStream("E:\\test\\data4.txt"); 9 | //构建输出流字节字符转换对象 10 | OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); 11 | //构建字符输出流对象 12 | BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); 13 | 14 | //构建数据 15 | char[] chars = new char[3]; 16 | chars[0] = 'a'; 17 | chars[1] = 'b'; 18 | chars[2] = '中'; 19 | 20 | //输出数据 21 | bufferedWriter.write(chars); 22 | 23 | //关闭流 24 | bufferedWriter.close(); 25 | outputStreamWriter.close(); 26 | fileOutputStream.close(); 27 | 28 | } catch (FileNotFoundException e) { 29 | e.printStackTrace(); 30 | } catch (IOException e) { 31 | e.printStackTrace(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src8/fileRW/Person.java: -------------------------------------------------------------------------------- 1 | package fileRW; 2 | import java.io.*; 3 | //https://juejin.cn/post/6844903848167866375 4 | public class Person implements Serializable { 5 | private String name; 6 | private int age; 7 | public Person(String name, int age) { 8 | this.name = name; 9 | this.age = age; 10 | } 11 | //为了方便查看对象,重写默认的toString() 12 | @Override 13 | public String toString(){ 14 | return "Person{" + "name='" + name + '\'' + ", age=" + age +'}'; 15 | } 16 | } 17 | 18 | 19 | -------------------------------------------------------------------------------- /src8/fileRW/SeriDemo.java: -------------------------------------------------------------------------------- 1 | package fileRW; 2 | import java.io.*; 3 | public class SeriDemo { 4 | public static void main(String[] args) { 5 | // ObjectOutputStream 流 6 | try { 7 | Person p1 = new Person("zhangsan", 30); 8 | System.out.println(p1); 9 | ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("sample_files/person.dat")); 10 | oos.writeObject(p1); 11 | } catch (Exception e) { 12 | e.printStackTrace(); 13 | } 14 | 15 | //创建一个ObjectInputStream输入流 16 | try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("sample_files/person.dat"))){ 17 | System.out.println("readObject():"); 18 | Person zhangsan = (Person) ois.readObject(); 19 | System.out.println(zhangsan); 20 | } catch (Exception e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | 26 | 27 | 28 | 29 | 30 | 31 | // 32 | // public static void main(String[] args){ 33 | // try { 34 | // Person p1= new Person("zhangsan", 30); 35 | // Person p2= new Person("lisi", 40); 36 | // System.out.println(p1); 37 | // System.out.println(p1); 38 | // Person[] plist = new Person[2]; 39 | // plist[0] = p1; 40 | // plist[1] = p2; 41 | // ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat")); 42 | // oos.writeObject(plist); 43 | // } 44 | // catch (Exception e) { 45 | // e.printStackTrace(); 46 | // } 47 | // 48 | // 49 | // try { 50 | // //创建一个ObjectInputStream输入流 51 | // ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"))) 52 | // Person plist = (Person[]) ois.readObject(); 53 | // System.out.println(brady); 54 | // } catch (Exception e) { 55 | // e.printStackTrace(); 56 | // } 57 | -------------------------------------------------------------------------------- /src8/fileRW/example_files.java: -------------------------------------------------------------------------------- 1 | package fileRW; 2 | import java.io.*; 3 | import java.nio.file.*; 4 | import java.util.*; 5 | 6 | public class example_files { 7 | public static void main(String[] args) throws IOException { 8 | // 定义一个目录路径的Path对象 9 | Path directoryPath = Paths.get("sample_files"); 10 | // 根据Path对象创建多级目录 11 | Files.createDirectories(directoryPath); 12 | System.out.println("目录创建成功!"); 13 | // 定义一个文件路径的Path对象 14 | Path filePath = Paths.get("sample_files/test.txt"); 15 | // 根据Path对象创建一个文件 16 | Files.createFile(filePath); 17 | // 创建一个List集合,并向集合中添加内容 18 | List list = new ArrayList<>(); 19 | list.add("这是一个测试文件"); 20 | // 将集合中的内容追加写入到指定的文件中 21 | Files.write(filePath, list, StandardOpenOption.APPEND); 22 | List lines = Files.readAllLines(filePath); 23 | System.out.println("文件的大小为:" + Files.size(filePath)); 24 | System.out.println("文件中的内容为:" + lines); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /src8/fileRW/fileStreamTest.java: -------------------------------------------------------------------------------- 1 | package fileRW; 2 | import java.io.*; 3 | public class fileStreamTest { 4 | public static void main(String[] args) throws IOException { 5 | File f = new File("sample_files/a.txt"); 6 | FileOutputStream fop = new FileOutputStream(f); 7 | // 构建FileOutputStream对象,文件不存在会自动新建 8 | OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8"); 9 | // 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码 10 | writer.append("中文输入"); 11 | // 写入到缓冲区 12 | writer.append("\r\n"); 13 | // 换行 14 | writer.append("English"); 15 | 16 | writer.close(); 17 | // 关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉 18 | fop.close(); 19 | // 关闭输出流,释放系统资源 20 | 21 | FileInputStream fip = new FileInputStream(f); 22 | // 构建FileInputStream对象 23 | 24 | InputStreamReader reader = new InputStreamReader(fip, "UTF-8"); 25 | // 构建InputStreamReader对象,编码与写入相同 26 | 27 | StringBuffer sb = new StringBuffer(); 28 | while (reader.ready()) { 29 | sb.append((char) reader.read()); 30 | // 转成char加到StringBuffer对象中 31 | } 32 | 33 | 34 | System.out.println(sb.toString()); 35 | reader.close(); 36 | // 关闭读取流 37 | 38 | fip.close(); 39 | // 关闭输入流,释放系统资源 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src9/mvc/MVCPatternDemo.java: -------------------------------------------------------------------------------- 1 | package mvc; 2 | 3 | //演示MVC模式,客户端可以感知的只有视图和控制器 4 | public class MVCPatternDemo { 5 | public static void main(String[] args) { 6 | 7 | //从数据库获取学生记录 8 | Student model = retrieveStudentFromDatabase(); 9 | 10 | //创建一个视图:把学生详细信息输出到控制台 11 | StudentView view = new StudentView(); 12 | 13 | StudentController controller = new StudentController(model, view); 14 | 15 | controller.updateView(); 16 | 17 | //更新模型数据 18 | controller.setStudentName("John"); 19 | 20 | controller.updateView(); 21 | } 22 | 23 | private static Student retrieveStudentFromDatabase(){ 24 | Student student = new Student(); 25 | student.setName("Robert"); 26 | student.setRollNo("10"); 27 | return student; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src9/mvc/Student.java: -------------------------------------------------------------------------------- 1 | package mvc; 2 | 3 | //创建模型Model 4 | public class Student { 5 | private String rollNo; 6 | private String name; 7 | public String getRollNo() { 8 | return rollNo; 9 | } 10 | public void setRollNo(String rollNo) { 11 | this.rollNo = rollNo; 12 | } 13 | public String getName() { 14 | return name; 15 | } 16 | public void setName(String name) { 17 | this.name = name; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src9/mvc/StudentController.java: -------------------------------------------------------------------------------- 1 | package mvc; 2 | 3 | //创建控制器:StudentController,其中定义了用户的很多请求 4 | public class StudentController { 5 | private Student model; 6 | private StudentView view; 7 | 8 | public StudentController(Student model, StudentView view){ 9 | this.model = model; 10 | this.view = view; 11 | } 12 | 13 | public void setStudentName(String name){ 14 | model.setName(name); 15 | } 16 | 17 | public String getStudentName(){ 18 | return model.getName(); 19 | } 20 | 21 | public void setStudentRollNo(String rollNo){ 22 | model.setRollNo(rollNo); 23 | } 24 | 25 | public String getStudentRollNo(){ 26 | return model.getRollNo(); 27 | } 28 | 29 | public void updateView(){ 30 | view.printStudentDetails(model.getName(), model.getRollNo()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src9/mvc/StudentView.java: -------------------------------------------------------------------------------- 1 | package mvc; 2 | 3 | //创建视图View 4 | public class StudentView { 5 | public void printStudentDetails(String studentName, String studentRollNo){ 6 | System.out.println("Student: "); 7 | System.out.println("Name: " + studentName); 8 | System.out.println("Roll No: " + studentRollNo); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src9/swingTest/BorderLayoutDemo.java: -------------------------------------------------------------------------------- 1 | package swingTest; 2 | 3 | import javax.swing.JButton; 4 | import javax.swing.JFrame; 5 | import java.awt.*; 6 | public class BorderLayoutDemo 7 | { 8 | public static void main(String[] agrs) 9 | { 10 | JFrame frame=new JFrame("Java GUI程序"); //创建Frame窗口 11 | frame.setSize(400,200); 12 | frame.setLayout(new BorderLayout()); //为Frame窗口设置布局为BorderLayout 13 | JButton button1=new JButton ("上"); 14 | JButton button2=new JButton("左"); 15 | JButton button3=new JButton("中"); 16 | JButton button4=new JButton("右"); 17 | JButton button5=new JButton("下"); 18 | frame.add(button1,BorderLayout.NORTH); 19 | frame.add(button2,BorderLayout.WEST); 20 | frame.add(button3,BorderLayout.CENTER); 21 | frame.add(button4,BorderLayout.EAST); 22 | frame.add(button5,BorderLayout.SOUTH); 23 | frame.setBounds(300,200,600,300); 24 | frame.setVisible(true); 25 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 26 | } 27 | } -------------------------------------------------------------------------------- /src9/swingTest/ButtonFrame.java: -------------------------------------------------------------------------------- 1 | package swingTest; 2 | 3 | import java.awt.*; 4 | import javax.swing.*; 5 | import java.awt.event.*; 6 | public class ButtonFrame extends JFrame { 7 | private JPanel buttonPanel; 8 | private static final int DEFAULT_WIDTH = 300; 9 | private static final int DEFAULT_HEIGHT = 200; 10 | 11 | public ButtonFrame() { 12 | setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 13 | JButton YellowButton = new JButton("Yellow"); 14 | JButton BlueButton = new JButton("Blue"); 15 | JButton RedButton = new JButton("Red"); 16 | 17 | //重复的步骤,可以创建一个辅助方法 18 | buttonPanel = new JPanel(); 19 | buttonPanel.add(YellowButton); 20 | buttonPanel.add(BlueButton); 21 | buttonPanel.add(RedButton); 22 | add(buttonPanel); 23 | ColorAction YellowAction = new ColorAction(Color.YELLOW); 24 | ColorAction BlueAction = new ColorAction(Color.BLUE); 25 | ColorAction RedAction = new ColorAction(Color.RED); 26 | YellowButton.addActionListener(YellowAction); 27 | BlueButton.addActionListener(BlueAction); 28 | RedButton.addActionListener(RedAction); 29 | } 30 | 31 | /** 32 | * An action listener that sets the panel's background color. 33 | */ 34 | private class ColorAction implements ActionListener { 35 | private Color backgroundColor; 36 | 37 | public ColorAction(Color C) { 38 | backgroundColor = C; 39 | } 40 | 41 | public void actionPerformed(ActionEvent event) { 42 | buttonPanel.setBackground(backgroundColor); 43 | } 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /src9/swingTest/ButtonFrame2.java: -------------------------------------------------------------------------------- 1 | package swingTest; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.awt.event.ActionEvent; 6 | import java.awt.event.ActionListener; 7 | 8 | public class ButtonFrame2 extends JFrame 9 | { 10 | private JPanel buttonPanel; 11 | private static final int DEFAULT_WIDTH = 300; 12 | private static final int DEFAULT_HEIGHT = 200; 13 | 14 | public ButtonFrame2() 15 | { 16 | setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 17 | buttonPanel = new JPanel(); 18 | add(buttonPanel); 19 | makeButton("yellow",Color.YELLOW); 20 | makeButton("blue",Color.BLUE); 21 | makeButton("red",Color.RED); 22 | makeButton("green",Color.GREEN); 23 | } 24 | public void makeButton(String name , Color backgroundColor) 25 | { 26 | JButton button=new JButton(name); 27 | buttonPanel.add(button); 28 | ColorAction action=new ColorAction(backgroundColor); 29 | button.addActionListener(action); 30 | } 31 | /** 32 | * An action listener that sets the panel's background color. 33 | */ 34 | private class ColorAction implements ActionListener 35 | { 36 | private Color backgroundColor; 37 | public ColorAction(Color c) 38 | { 39 | backgroundColor = c; 40 | } 41 | public void actionPerformed(ActionEvent event) 42 | { 43 | buttonPanel.setBackground(backgroundColor); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src9/swingTest/ButtonFrame2Test.java: -------------------------------------------------------------------------------- 1 | package swingTest; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.awt.*; 6 | import javax.swing.*; 7 | import java.awt.event.*; 8 | 9 | public class ButtonFrame2Test { 10 | public static void main(String[] args) 11 | { 12 | EventQueue.invokeLater(()->{ 13 | JFrame frame=new ButtonFrame2(); 14 | frame.setTitle("ListenerTest"); 15 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 | frame.setVisible(true); 17 | } 18 | ); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src9/swingTest/ButtonFrameTest.java: -------------------------------------------------------------------------------- 1 | package swingTest; 2 | 3 | import java.awt.*; 4 | import javax.swing.*; 5 | import java.awt.event.*; 6 | 7 | public class ButtonFrameTest { 8 | public static void main(String[] args) 9 | { 10 | EventQueue.invokeLater(()->{ 11 | JFrame frame=new ButtonFrame(); 12 | frame.setTitle("ListenerTest"); 13 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 14 | frame.setVisible(true); 15 | } 16 | ); 17 | } 18 | } -------------------------------------------------------------------------------- /src9/swingTest/SimpleFrame.java: -------------------------------------------------------------------------------- 1 | package swingTest; 2 | 3 | import javax.swing.JFrame; 4 | class SimpleFrame extends JFrame{ 5 | private static final int DEFAULT_WIDTH = 300; 6 | private static final int DEFAULT_HEIGHT = 200; 7 | public SimpleFrame(){ 8 | setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src9/swingTest/SimpleFrameTest.java: -------------------------------------------------------------------------------- 1 | package swingTest; 2 | 3 | import javax.swing.JFrame; 4 | import java.awt.*; 5 | public class SimpleFrameTest { 6 | public static void main(String[] args){ 7 | EventQueue.invokeLater(()-> 8 | { 9 | SimpleFrame frame = new SimpleFrame(); 10 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11 | frame.setVisible(true); 12 | }); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src9/swingTest/TestController.java: -------------------------------------------------------------------------------- 1 | package swingTest; 2 | 3 | //https://www.geek-share.com/detail/2652038835.html 4 | import java.awt.BorderLayout; 5 | import java.awt.event.ActionEvent; 6 | import java.awt.event.ActionListener; 7 | 8 | import javax.swing.JFrame; 9 | import javax.swing.JPanel; 10 | 11 | public class TestController { 12 | private TestView testview; 13 | private TestModel testmodel; 14 | 15 | public TestController() { 16 | testview=new TestView(); 17 | testmodel=new TestModel(); 18 | testview.addActionListener(new ActionListener() { 19 | public void actionPerformed(ActionEvent e) { 20 | System.out.println("suc..."); 21 | testmodel.setMessage("test..."); 22 | testview.setTextArea(testmodel.getMessage()); 23 | } 24 | }); 25 | 26 | } 27 | public JPanel getView(){ 28 | return testview; 29 | } 30 | 31 | public static void main(String[] args) { 32 | TestController testcontroller=new TestController(); 33 | JFrame frame=new JFrame("TEST"); 34 | frame.setLayout(new BorderLayout()); 35 | frame.setBounds(100, 100, 450, 300); 36 | frame.getContentPane().add(testcontroller.getView()); 37 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 38 | frame.setVisible(true); 39 | 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src9/swingTest/TestModel.java: -------------------------------------------------------------------------------- 1 | package swingTest; 2 | //https://www.geek-share.com/detail/2652038835.html 3 | 4 | public class TestModel { 5 | private String message; 6 | 7 | public String getMessage(){ 8 | return message; 9 | } 10 | public void setMessage(String message){ 11 | this.message=message; 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /src9/swingTest/TestView.java: -------------------------------------------------------------------------------- 1 | package swingTest; 2 | 3 | //https://www.geek-share.com/detail/2652038835.html 4 | import java.awt.event.ActionEvent; 5 | import java.awt.event.ActionListener; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | import javax.swing.JButton; 10 | import javax.swing.JPanel; 11 | import javax.swing.JTextArea; 12 | 13 | public class TestView extends JPanel{ 14 | private static final long serialVersionUID = 1L; 15 | private JTextArea textArea; 16 | private List listeners; 17 | public void addActionListener(ActionListener actionlistener){ 18 | listeners.add(actionlistener); 19 | } 20 | public void setTextArea(String text){ 21 | textArea.setText(text); 22 | } 23 | 24 | public TestView() { 25 | listeners=new ArrayList(); 26 | setLayout(null); 27 | textArea=new JTextArea(); 28 | textArea.setBounds(20, 20, 400, 100); 29 | add(textArea); 30 | JButton textbtn=new JButton("Show Message"); 31 | textbtn.setBounds(120, 140, 150, 40); 32 | add(textbtn); 33 | textbtn.addActionListener(new ActionListener() { 34 | public void actionPerformed(ActionEvent e) { 35 | for(int i=0;i