1/173
Midterm/Final
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
How do you represent an inheritance in a UML class diagram?
solid line with a triangle (IS-A)
How do you represent an interface in a UML class diagram?
dashed line with a triangle.
How do you represent an association in a UML class diagram?
solid line between two classes that indicates a relationship between them.
In a UML diagram if a piece of text is in italics, then it’s what?
Abstract
In a UML Diagram, when there is an arrow pointed in one direction what does that mean?
That indicates a directed relationship.
In a UML class diagram, what does a filled diamond mean?
It represents a composition relationship, indicating that one class is a part of another and cannot exist independently.
In a UML class diagram, what is aggregation (weak)?
Represented as an open diamond, indicating a whole-part relationship where the part can exist independently.
In a UML diagram, public is represented as what?
+
In a UML diagram, private is represented as what?
-
In a UML diagram, protected is represented as what?
#
In a UML diagram, package is represented as what?
~
what does the top compartment of a UML class contain?
Class name and what type of class it is
what does the middle compartment of a UML class contain?
Attributes and their visibility
What does the bottom compartment of a UML class contain?
Methods and their visibility
What is Javadoc?
Javadoc is a tool provided by Java that automatically generates HTML documentation from specially formatted comments in Java source code.
What do Javadoc comments begin and end with?
/** and end with /
In Javadoc, what tag describes method parameters
@param
In Javadoc, what tag describes the method’s return value?
@return
In Javadoc, what tag specifies exceptions thrown by the method?
@throws
In Javadoc, what tag links to other classes, methods, or fields?
@see
In Javadoc, what tag marks methods that should no longer be used?
@deprecated
In Javadoc, what tag adds an "Author" entry with the specified name-text to the generated docs?
@author
The first sentence of a Javadoc comment is what?
Summary sentence that provides a brief overview of the method or class's purpose.
In Anti-Patterns, what is a God-Object?
A class or module that becomes excessively large and takes on too many responsibilities.
In Anti-Patterns, what is an Anemic Domain Model?
When domain objects lack behavior or business logic and serve primarily as data containers.
In Anti-Patterns, what is Spaghetti code?
Characterized by tangled and poorly structured logic, often resulting from ad-hov development without proper planning or design.
In Anti-Patterns, what is copy-paste programming?
Involves duplicating code instead of abstracting common functionality into reusable components.
In Anti-Patterns, what is constant interface?
Where an interface is used solely to declare a set of consistent variables instead of using a class to define constants.
In Anti-Patterns, what is “Not Invented Here”?
The tendency of developers to reject existing solutions or libraries in favor of building their own from scratch
In Anti-Patterns, what is “Feature Envy”?
When a method or function in one class excessively accesses the data or methods of another class, rather than relying on its data and behavior.
In Anti-Patterns, what is “Dead Code”?
Unreferenced or unreachable portions of the codebase that no longer serve a purpose
In Anti-Patterns, what is “Magic Numbers”?
Hard-coded numbers that are scattered throughout the codebase without any explanations.
In Anti-Patterns, what are “Hardcoding configurations”?
Hardcoding configuration settings, such as database connection strings or API endpoints, directly into the codebase make it inflexible and difficult to manage across different environments.
In Anti-Patterns, what are “Code Smells”?
indications of potential problems in the codebase, such as long methods, large classes, or excessive comments.
In Anti-Patterns, what is “The Swiss Army Knife”?
when a software component or module is designed to be overly general-purpose and flexible, trying to accommodate various use cases and requirements. This results in bloated code, increased complexity, and decreased performance.
True or False. Monostate defines a “conceptual singleton”
True
Why is monostate not a true singleton?
Because it allows multiple instances to exist while sharing the same state.
What is the difference between power type and Flyweight design pattern?
Both are designed to eliminate the need for duplicate objects, but the Flyweight pattern focuses on sharing objects to support a large number of similar objects efficiently, while the Power Type pattern enhances type safety by creating subclasses for specific behaviors.
What design pattern is shown in the UML?
Strategy because the interface delegates behaviors to the correct implementation.
What design pattern is demonstrated in the image?
Power Type I know this because the code splits the class into two classes. One for unique data and another for shared, unchanged data to optimize memory usage.
What 2 patterns help to manage state and data more efficiently?
Monostate and Power Type. Monostate because it allows a shared state across multiple instances, and Power Type because it reduces memory waste and maintains consistency across objects that share common data.
public interface WeatherSubject {
void registerWeatherObserver(WeatherObserver wo, double percentChange) throws SomeException; // keeps track of observers that want to be notified
void registerWeatherObserver(WeatherObserver wo) throws SomeException;
void removeWeatherObserver(WeatherObserver wo); //A way to unregister people
void notifyWeatherObservers();// notifies the observers
}
What design pattern is this? How do you know?
Observer because it implements code that allows for one object to notify multiple observer objects when the state changes.
Define Null Object
provides a default object with empty or default behavior, avoiding the need for repeated null checks in the code.
What design pattern would best fit the image and why?
Monostate because all instances will see and share the same values for the data attributes.
What design pattern would best fit a checkers game where players can undo bad moves?
Memento design pattern
What design pattern does this image imply?
A flyweight pattern because it shares an instance of the same data that we can retrieve
import java.util.HashMap;
import java.util.Map;
class Price {
private final String value; // Immutable
private Price(String value) {
this.value = value;
}
public String getValue() {
return value;
}
// Example of an operation
public Price add(Price anotherPrice) {
double sum = Double.parseDouble(this.value) + Double.parseDouble(anotherPrice.getValue());
return PriceFactory.getPrice(String.format("%.2f", sum)); // Use Factory to get Flyweight instance
}
}
class PriceFactory {
private static final HashMap<Integer, Price> price = new HashMap<>();
// Method to get an existing price or create a new one if not found
public static Price getPrice(int value) {
if (!prices.containsKey(value)) {
price p = new Price(value);
priceMap.put(value, p);
}
return price.get(value);
}
}
public class Example {
public static void main(String[] args) {
Price price1 = PriceFactory.getPrice("100.00");
Price price2 = PriceFactory.getPrice("100.00");
Price price3 = PriceFactory.getPrice("50.00");
System.out.println("Price1 == Price2: " + (price1 == price2)); // True, same object reference
System.out.println("Price1 == Price3: " + (price1 == price3)); // False, different object references
Price sumPrice = price1.add(price3);
System.out.println("Sum Price: " + sumPrice.getValue()); // Sum of the two prices
}
}
What design pattern is this? how do you know?
The Flyweight pattern because it uses a static HashMap
in PriceFactory
to store and reuse Price
objects, minimizing memory usage by sharing instances instead of creating multiple identical objects.
public class USAircraft{
private USAircraft(){} // Static methods, no reason to “new”
public static Aircraft createAircraft( String type){
if (type.equals(“LightTransport”)
returnnew LightTransportCraft();
else if (type.equals(“HeavyTransport”)
return new HeavyTransportCraft();
else if (type.equals(“Troop”))
return new TroopTransportCraft();
else if (type.equals(“Fighter”))
return new FighterCraft();
else if (type.equals(“Bomber”))
return new BomberCraft();
else if (type.equals(“Gunship”))
return new GunshipCraft();
else if (type.equals(“Medic”))
return new MedicHelicopterCraft();
else return null; // Don’t know what this is…
}
}
What design pattern is this?
Factory
From this image, what design pattern would help this implementation? and why?
The facade pattern because it can create a single class that provides a simple interface to the complex system.
// Main
public class Laboratory {
public static void main(String[] args) {
System.out.println();
System.out.println("-- Research Laboratory --");
System.out.println();
Employee investigator01 = new PrincipleInvestigator();
investigator01 = new SafetyCaptain(investigator01);
System.out.println(investigator01.getTitle() +
"\n\tResponsibilities include " investigator01.getResponsibility());
Employee investigator02 = new PrincipleInvestigator();
investigator02 = new SafetyCaptain(investigator02);
**investigator02 = new BloodDriveCanvasser(investigator02);**
System.out.println(investigator02.getTitle() +
"\n\tResponsibilities include " + investigator02.getResponsibility());
Employee technician = new ResearchTechnician();
**technician = new ComputerSecurityOfficer(technician);**
technician = new BloodDriveCanvasser(technician);
System.out.println(technician.getTitle() +
"\n\tResponsibilities include " + technician.getResponsibility());
Employee admin = new AdministrativeAssistant();
admin = new BloodDriveCanvasser(admin);
System.out.println(admin.getTitle() +
"\n\tResponsibilities include " + admin.getResponsibility());
}
}
//usage
Employee technician = new ResearchTechnician();
technician = new SafetyCaptain(technician);
System.out.println(technician.getTitle()); // Outputs: Research Technician, Safety Captain
What design pattern does this main imply? and how do you know?
Decorator because the calls are wrapping around an interface or implementation in order to dynamically change its behavior
What UML design pattern is this?
Composite design pattern
public interface PackageComponent {
double getWeight();
String getId();
void addPackage(PackageComponent pc) throws Exception;
PackageComponent getPackage(String id);
int getPackageCount();
}
public class Package implements PackageComponent {
private String identifier;
private double weight;
public Package(String id, double w) {
this.identifier = id;
this.weight = w;
}
public double getWeight() {
return weight;
}
public String getId() {
return identifier;
}
public void addPackage(PackageComponent pc) throws Exception {
throw new Exception("A Package cannot have Packages added to it!");
}
public PackageComponent getPackage(String id) {
return null;
}
public int getPackageCount() {
return 1; // A single package
}
}
public class ShippingContainer implements PackageComponent {
private String identifier;
private HashMap<String, PackageComponent> items = new HashMap<String, PackageComponent>();
public ShippingContainer(String id) {
this.identifier = id;
}
public double getWeight() {
double totalWeight = 0;
for (PackageComponent pc: items.values()) {
totalWeight += pc.getWeight();
}
return totalWeight;
}
public String getId() {
return identifier;
}
public void addPackage(PackageComponent p) {
items.put(p.getId(), p);
}
public PackageComponent getPackage(String id) {
if (items.containsKey(id)) {
return items.get(id);
}
for (PackageComponent pc : items.values()) {
PackageComponent found = pc.getPackage(id);
if (found != null) return found;
}
return null;
}
public int getPackageCount() {
int totalCount = 0;
for (PackageComponent pc : items.values()) {
totalCount += pc.getPackageCount();
}
return totalCount;
}
}
public class Ship {
private HashMap<String, PackageComponent> cargo = new HashMap<>();
public double getWeight() {
double totalWeight = 0;
for (PackageComponent pc : cargo.values()) {
totalWeight += pc.getWeight();
}
return totalWeight;
}
public void addPackage(PackageComponent p) {
cargo.put(p.getId(), p);
}
public PackageComponent getPackage(String id) {
if (cargo.containsKey(id)) {
return cargo.get(id);
}
for (PackageComponent pc : cargo.values()) {
PackageComponent found = pc.getPackage(id);
if (found != null) return found;
}
return null;
}
public int getPackageCount() {
int totalCount = 0;
for (PackageComponent pc : cargo.values()) {
totalCount += pc.getPackageCount();
}
return totalCount;
}
}
What design pattern is this? And how do you know?
This is a Composite pattern because it allows both individual items (packages) and groups of items (containers) to be treated the same way through a shared interface, PackageComponent
.
What design pattern is this? and how do you know?
```java
public class EnvironmentMgr {
_// Static attributes shared across all instances_
private static double temperature;
private static double humidity;
_// Accessor methods_
public double getTemperature() {
return temperature;
}
public void setTemperature(double temperatureIn) {
temperature = temperatureIn;
}
public double getHumidity() {
return humidity;
}
public void setHumidity(double humidityIn) {
humidity = humidityIn;
}
}
Monostate because it uses a static reference, but looks like a singleton.
Whats the difference between Monostate and Singleton?
The Singleton pattern ensures only one instance of a class exists, while the Monostate pattern allows multiple instances but ensures they all share the same state by having static data members.
Define the flyweight design pattern
optimizes memory by minimizing the number of duplicate objects by sharing one object among all instances requiring the same state.
What other design pattern does the flyweight pattern use?
Factory
How is the Factory design pattern used in the flyweight design pattern?
it’s used to manage object creation, ensuring that no duplicate objects are created. If a requested object already exists, the Factory returns a reference to the existing object instead of creating a new one.
True or False. Flyweight objects are immutable
True
What design pattern is this?
Decorator
Define Liskov Substitution Principle
If a program uses a base class, it should be able to use any derived class without the program breaking. This ensures inheritance is used correctly.
Whats the difference between comparable and compareTo?
Comparable is an interface, while compareTo is a method within that interface that compares the current object with another object to determine its relative order.
Define Association Composition
offers greater FLEXIBILITY because the relationships among the visible parts can be redefined at run-time.
Define Aggregation Composition
allows for greater SECURITY because its structure is defined in advance, and cannot be altered at run-time.
Define Information Hiding
when we hide the details of the design, algorithms, and data structures that may change over time and expose methods that won't change
Define Abstraction
a model that contains the most important aspects of something.
Why is abstraction important?
Because it can simplify a complex situation based on the real world
Which design patterns are often seen in addition to the Facade pattern?
A) Strategy
B) Data Transfer Object
C) Singleton
D) Factory
B and D
Which design patterns are often seen in addition to the Strategy Pattern?
A) Null Object
B) Data Transfer Object
C) Singleton
D) Factory
A and D
Which design patterns are often seen in addition to the Data Transfer Object pattern?
A) Facade
B) Factory
C) Strategy
D) Null Object
A
Singleton
Ensures that a class can only have one instance and provides a global access point to the one instance.
Facade
Specifies the creation of a class with a simple interface to a complex subsystem or complex set of entities, decoupling the subsystem from client classes and other subsystems.
Dependency Inversion Principle
Specifies that you should code to an interface, not to an implementation.
Strategy
Allows multiple implementation classes to be created when a variety of algorithms are needed to handle interface behaviors.
Open-Closed Principle
Indicates that when requirements change, you can extend the behavior of such modules by adding new code, not by changing old code that already works.
Data Transfer Object
Often used in conjunction with the "Facade" pattern to encapsulate only key certain data elements of a domain object in a simple class.
Single Responsibility Principle
There should never be more than one reason for a class to change.
Encapsulation
Principle which states that data members, and the methods that operate on that data, must exist in the same class.
Inheritance
Defines a technique in which a class can inherit characteristics and features from more than one superclass.
Factory
Insulates client code from the details of object creation by having clients request the creation of an object, and results in an appropriate object being created and returned to the caller
Polymorphism
The idea of allowing the same code to be used with different types of related objects, resulting in more general and abstract implementations.
Static
Indicates that the data attribute or method is "owned" by the class, not by objects (instances of the class).
Separation
Specifies that the "interface" to a class or subsystem must be distinct and decoupled from the "implementation" of that class or subsystem.
Composition relationships generally fall into categories: aggregations and associations.
Which is true about these 2 composition types? (Circle all that apply). (3 pts)
a) In an aggregation relationship, the "parts" are visible and accessible. b)
b) In an aggregation relationship, the "parts" are not visible or accessible.
c) In an association relationship, the "parts" are not visible or accessible.
d) In an association relationship, the "parts" are visible and accessible.
e) None of these are correct.
B and D
True or False:
A class acting as a Factory that creates different types of objects that implement the same interface cannot return the objects using the interface type.
False
True or False:
The Singleton design pattern ensures that only one object of a class. This is managed within the class by implementing a static counter that will have the value 0 (no object yet created) or 1 (the single object has been created).
False
Identify the Design Pattern or Patterns present in the following java code and explain why. (Check all that apply).
public final class Environment {
private static Environment instance;
// Private constructor to prevent instantiation
private Environment() {}
// Method to get the singleton instance
public static Environment getInstance() {
if (instance == null) {
instance = new Environment();
}
return instance;
}
// Method to get temperature at coordinates (x, y)
public double getTemperature(int x, int y) {
// Complex weather-resource code goes in here
return 0.0; // Placeholder return
}
// Method to get humidity at coordinates (x, y)
public double getHumidity(int x, int y) {
// Complex weather-resource code goes in here
return 0.0; // Placeholder return
}
}
A) Singleton
B) Data Transfer Object
C) Facade
D) Factory
E) Strategy
F) Null Object
G) None of these
H) All of these
Singleton and Facade because it uses one instance of Environment
, and the Facade pattern because it provides simplified methods (getTemperature
and getHumidity
) to access complex functionality.
Identify the Design Patterns or Patterns present in the following java code and explain why. (Check all that apply)
public class CalcMaker {
if (style. equals ("BASIC")) {
return BasicCalculator (metric);
}else if (style.equals("SCIENTIFIC")){
return ScientificCalculator (metric);
}else {
return DefaultCalculator (metric);
A) Singleton
B) Data Transfer Object
C) Facade
D) Factory
E) Strategy
F) Null Object
G) None of these
H) All of these
Its Factory because It creates different types of calculators (BasicCalculator
, ScientificCalculator
, DefaultCalculator
) based on the given style
, and its Facade because It provides a unified interface (CalcMaker
) to create calculators, simplifying access to different calculator types by hiding the complexity of their instantiation.
public class CustomerData {
public String customerId;
public String lastName;
public String firstName;
public double avgPurchase;
public int purchaseCount;
public CustomerData(String ci,String In,String fn, double ap, int pc) {
customerId = ci;
lastName = rn;
firstName = fn;
avgPurchase = ap;
purchaseCount = pc;
}
}
What design pattern is shown in the code?
A) Singleton
B) Data Transfer Object
C) Facade
D) Factory
E) Strategy
F) Null Object
G) None of these
H) All of these
B
Data Transfer Object
Does this refer to inheritance or Interface?
“Used to define a “Role” and the behaviors that role requires”
Interface
Does this refer to inheritance or Interface?
Best used to encapsulate structural commonalities
Inheritance
Does this refer to inheritance or Interface?
Can only include constant (final) data members.
Interface
Does this refer to inheritance or Interface?
Defines a parent-child relationship.
Inheritance
Does this refer to inheritance or Interface?
Allows you build a new class based on an existing class's implementation.'
Inheritance
Does this refer to inheritance or Interface?
Best used to encapsulate behavioral commonalities.
Interface
Does this refer to inheritance or Interface?
Involves extension by other classes.
Inheritance
Does this refer to inheritance or Interface?
Couples two classes together.
Inheritance
Does this refer to inheritance or Interface?
Used with the Strategy design pattern.
Interface
Does this refer to inheritance or interface?
Used in conjunction with Delegation
Interface
Does this refer to inheritance or Interface?
Involves implementation by other classes.
Interface
Does this refer to inheritance or Interface?
Can include methods with public, private, protected, or package visibility.
Inheritance