fabiochiu/medium-articles huggingface dataset:
PHP design patterns (Creational : part 1)
By: Michael Manga
Tags: PHP, Design Patterns, Code Patterns, Php Development

I recently discovered a great open source project, presenting various data structures for PHP. I decided to interest in it.

Here is the link of the project’s Github repository : https://github.com/domnikl/DesignPatternsPHP

Let’s start by presenting the first creational pattern listed there :

Simple factory

This method simply consists in dedicating a specific “factory”, (the word is pretty self descriptive ) to handle objects instanciations.

Let’s imagine that need to use “products” objects, to use inside your project.

Instead of the usual:

$product = new Product('super product');

do :

class createProducts { public static function makeProduct(string $name ){ return new Product($name); }

}

Then, here is how you can instanciate the object.

$product = createProducts::makeProduct('my product');

Nothing that different, but it’s a way to organize the code in a “cleaner” way, especially when there is more and more complexity involved.
Patrones de Diseño: Patrón Estrategia en JavaScript
By: Carlos Caballero
Tags: Design Patterns, Programming, Programación, JavaScript

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Что творится в голове у продуктового дизайнера
By: Никита Кондратьев
Tags: Design Patterns, UX Design, Product Design, Design Process, Design Thinking

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Strategy Pattern in Functional Java
By: Jose Figueredo
Tags: Functional Programming, Lambda Function, Strategy Pattern, Java, Design Patterns

Strategy is a behavioral design pattern that turns a set of behaviors into objects and makes them interchangeable inside original context object.

The original object, called context, holds a reference to a strategy object and delegates it executing the behavior. In order to change the way the context performs its work, other objects may replace the currently linked strategy object with another one.

Traditional approach

Let’s use as example a simple problem: we need to remove certain stuff from a string but we can use different ways to accomplish that. So the behavior is how the algorithm solves the problem.

RemoveStrategy: An abstraction of the algorithm. This is an interface having the abstract operation.

Remover class: A context class that doesn’t know how the concrete RemoveStrategy class is implemented but executes it and returns its results.

A concrete strategy that implements the algorithm.

In this case it removes white spaces in an imperative way using a for loop and comparing with an if statement.

Another concrete strategy that also removes white spaces but in a functional way using stream and filter.

Runner for the example:
PHP design patterns (Creational : part 2)
By: Michael Manga
Tags: PHP, Php Development, Code, Design Patterns

Let’s continue in our exploration of PHP data structures.

In the first episode, we talked about the “simple factory” pattern.

Now, we’ll go into a slightly more advanced structure.

Let’s talk about the Factory method:

The point of this pattern , can be compressed into one word : delegation.

Let’s imagine that just got an access to play to your favorite heroic fantasy video game.

Imagine there are 2 classes of characters to chose from :

Warriors

Druids

You decided to share the access of your account to two of your friends.

One of your friends like to play Warriors , while the other one likes to play Druids.

Here the character classes :

interface Character { public function attack();

} class Warrior implements Character { public function attack(){ echo 'the warrior attacks'; }

} class Druid implements Character {



public function attack(){ echo 'the Druid attacks'; } }

Let’s use an abstract class , representing the idea of delegation.

abstract class player{ abstract protected function createCharacter(): Character; public function attack(){ $character = $this->createCharacter();

$character->attack();

} } class friendA extends player{ protected function createCharacter(){ return new Warrior();

} } class friendB extends player{ protected function createCharacter(){ return new Thief(); } }

Now, you have 2 different friends, allowed to perform actions as a player. But even though they structurally use similar functions, they implement these functions in different fashions. They actually build distinct characters.
A Fábrica de Arquitetos VII - Mediator Pattern + MediatR
By: Lucas Eschechola
Tags: Dotnet, Mediator, Mediatr, Software Architecture, Design Patterns

Welcome, my name is Lucas and i’m 20 years old and i’m .Net Developer over 5 years ago. Let’s Code!
用 JavaScript 玩轉設計模式 | 各司其職的 Chain of Responsibility Pattern（責任鏈模式）
Tags: Chain Of Responsibility, JavaScript, Starbugs, Front End Development, Design Patterns

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
User Flows and Design Patterns: Etsy
By: Kelly Wong
Tags: User Experience, User Flow, UX Design, Design Patterns, Experience Design

I love Etsy, and with the holidays coming up, Etsy is probably the reason for my 40% increase in screen time. In this article, I will be looking at design patterns that I’ve observed throughout the Etsy website, as well as providing my own user flow for when I am navigating and purchasing items from the site.

Design Patterns

Modularity and color-coded items

Modularity

Etsy uses modular rectangular boxes to showcase different products for sale. The usage of modularity is clear in the image above, giving the user a consistent and structured shopping experience.

Color-Coded On Sale Items

Another design pattern that is utilized is the color-coded green text that signifies to the user that “hey this item is on sale!” This is also accessible to users because in addition to the colored text, there is also a strike through the old price.

Drop-down menu

Drop-Down Menu for Categories

Etsy utilizes hover-drop-down menus for a user-friendly shopping experience. With its many products and product types, this is essential for a website like Etsy. With hover-drop down menus, it allows the user to quickly scan and find the type of item they’re looking for without needing to enter a new page each time.

Reviews and Star Ratings

Reviews and Star Ratings

Modularity also appears in the Reviews section of a product. When a product is clicked, the user can scan the page for an overall star-rating, as well as look deeper into individual reviews.

User Flow

I’ve attached an example of my user flow for when I shop at Etsy. Overall, I have had positive experiences in shopping at Etsy, and appreciate the attention to detail that they provide to make their users’ experience a good one.
An iOS Engineer’s Perspective on SOLID Principles
By: Kelvin Tan
Tags: Swift, Xcode, Design Patterns, iOS, Programming

Principle #2: Open-Closed

Class should be opened for extension but closed for modification

This principle promotes writing a maintainable code by having two important characteristics:

Open for extension

Closed for modification

In short, you should be able to add almost any new feature to your class easily and won’t have to restructure your whole class, as we all know going through restructuring could result in additional time in development and testing.

I’m sure that as software engineers, we’re often reminded of building a customer-centric app, and that leads to a ton of new features coming from our product manager at the last minute. As a precautionary measure, always write code that’s scalable for some additional features.

Let’s use a really simple code example to illustrate the point. Imagine you own a zoo, and currently your zoo only houses a tiger. We got to be real — your aren’t going to make any money with only a tiger. You need more animals, so we need to build the zoo in a way that’ll allow us to add any animal at any time easily.

Code example

protocol AnimalProtocol { func makeSound() -> String } class Tiger: AnimalProtocol { func makeSound() -> String { return "Roar" } } struct Zoo { let animals: [AnimalProtocol] func animalNoise() -> [String] { return animals.map { $0.makeSound() } } } let tiger = Tiger() var zooAnimals = Zoo(animals: [tiger]) zooAnimals.animalNoise() // [roar]

We finally have a new addition of an animal and would like to add that into the zoo. Simple! Just create a new class, and add it into the zoo. And we’re good to go. Perhaps in the future, when we get more animals, we can just do the same thing.

Notice that I don’t modify much of the code above, but it’s still able to extend the functionality. Now that’s called scalability.
Lesson 23: The Visitor Pattern
By: Andrey Karazhev
Tags: Tutorial, Design Patterns, Visitor Pattern

The pattern belongs to the behavioral category of the design patterns.

Idea

Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Explanation

Wikipedia says:

In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures. It is one way to follow the open/closed principle.

In plain words:

The visitor allows adding new virtual functions to a family of classes, without modifying the classes.

Class Diagram

The class diagram will be:

Example

The task:

Let’s consider to inspect a database, web service and an application with a visitor.

Let’s define a service specification:

public interface Service {



void accept(final ServiceVisitor visitor);

}

We need to define a service visitor also:

public interface ServiceVisitor {



void visit(final Service service, final String name);

}

Let’s create services:

final class DbService implements Service {



@Override

public void accept(final ServiceVisitor visitor) {

visitor.visit(this, "Database service");

}

} final class WebService implements Service {

private final String name;



public WebService(final String name) {

this.name = name;

}



@Override

public void accept(final ServiceVisitor visitor) {

visitor.visit(this, name);

}

} final class Application implements Service {

private final List<Service> services;



public Application() {

this.services = List.of(new DbService(), new WebService("Web service"));

}



@Override

public void accept(final ServiceVisitor visitor) {

for (final Service service : services) {

service.accept(visitor);

}



visitor.visit(this, "Application");

}

}

We need to implement a visitor:

final class PerformVisitor implements ServiceVisitor {



@Override

public void visit(final Service service, final String name) {

System.out.println("Visited: " + name);

}

}

And then it can be used as:

final var app = new Application();

app.accept(new PerformVisitor());

app.accept((service, name) -> System.out.println("Test visited: " + name));

More Examples

Links
Template ve Strategy Tasarım Kalıplarını Birlikte Kullanmak
By: Halil İbrahim Altun
Tags: Oop, Design Patterns, C Sharp Programming

hialtun/MailSenderExample

Mail sender example using template pattern GitHub is home to over 50 million developers working together to host and…
Spring AOP 與 Java 動態代理
By: Bruce Hsu
Tags: Spring Aop, Java, Spring, Design Patterns, Proxy

Introduction to Spring AOP | Baeldung

In this tutorial, we'll introduce AOP (Aspect Oriented Programming) with Spring and start understanding how we can…
Software Design Patterns
By: Vasu Vanka
Tags: Design Patterns, Software Architecture, Software Engineering

There are multiple ways to design and develop a software product.

Will Explain 3 major software design patterns in this post.

design patterns are useful to achieve error free and best flow of data to a software product.

Class / Object Creational Pattern Adapter Pattern Template Pattern

Class / Object Creational Pattern :

Class / Object creational pattern can be referred as Creational Patterns. This pattern all about creation of object or class instance based on given requirement. find the scenarios where we can use this pattern.

Scenario 1: Create a class instance to maintain database connection between your application and DB. Creating a database connection for every database query is very expensive operation which will cause latency in response and uses unnecessary threads.

Here we will maintain Single database connection through out the application , this approach known as Singleton pattern.

Creational design patterns are the Factory Method, Abstract Factory, Builder, Singleton, Object Pool, and Prototype. Adapter Pattern :

Adapter pattern also known as structural pattern. This is used when we have distinct interfaces and have to establish a relation / communication between them.

Scenario 1: When you have a database API interface and 3rd Party API interface and you have to establish communication between then by maintaining a class instance which will take care of data handling from both the ends.

Structural design patterns are Adapter, Bridge, Composite, Decorator, Façade, Flyweight, Private Class Data, and Proxy. Template Pattern :

Template patterns also known as Behavior Pattern. This pattern about identifying common communication patterns between objects and realize these patterns.

Template pattern provides set of processing steps or a process defined template. User uses this template pattern as bare bone of the product to achieve desired functionality.

Template pattern can be extended without modifying existing flow.

Template patterns are Chain of responsibility, Command, Interpreter, Iterator, Mediator, Observer, State, Strategy, Template method, Visitor

If you like the post please tap on clap.
Our Current State of Innovative Prowess in Two Pictures
By: Gregory D Esau
Tags: Ecosystem Building, Rainforest, Innovation, Economy, Design Patterns

Photo by Dan Meyers on Unsplash

That is your basic primordial soup.

When it comes to innovation, that’s about where we’re at.

Here’s where we need to be, the standard to which we must strive before,

Nature.

Photo by Akash Banakar on Unsplash

Maybe you have lower standards than I do, but in schemes of design for a digital economy based on living systems, we’ve got a ways to go.
MVC คืออะไร? เดี๋ยวผมเล่าให้ฟัง
By: Arthorn Kittinukul
Tags: Igeargeek, Mvc, Design Patterns, Programming, Mvc Frameworks

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Lesson 22: The Template Method Pattern
By: Andrey Karazhev
Tags: Tutorial, Design Patterns, Template Patterns

The pattern belongs to the behavioral category of the design patterns.

Idea

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure. To make sure that subclasses don’t override the template method, the template method should be declared final.

Explanation

Wikipedia says:

In object-oriented programming, the template method is one of the behavioral design patterns identified by Gamma et al. in the book Design Patterns. The template method is a method in a superclass, usually an abstract superclass, and defines the skeleton of an operation in terms of a number of high-level steps. These steps are themselves implemented by additional helper methods in the same class as the template method.

In plain words:

Using the template method pattern, it’s possible to define the overall structure of the operation, while allowing subclasses to refine, or redefine, certain steps.

Class Diagram

The class diagram will be:

Example

The task:

Let’s consider to create a data loader that encodes data from different sources i.e. from a collection and stream.

Let’s define a data loader:

abstract class DataLoader {



abstract Collection<Integer> getData();



final String getEncoded() {

final var encoded = new StringBuilder();

getData().forEach(val -> encoded.append(":").append(val));

return encoded.length() > 0 ? encoded.deleteCharAt(0).toString() : encoded.toString();

}

}

We need to define a collection loader:

final class CollectionLoader extends DataLoader {

private final Collection<Integer> collection = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);



@Override

Collection<Integer> getData() {

return collection;

}

}

We need to define a stream loader:

final class StreamLoader extends DataLoader {

private final Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);



@Override

Collection<Integer> getData() {

return stream.collect(Collectors.toList());

}

}

And then it can be used as:

final var dataLoader = new CollectionLoader();

assertEquals("1:2:3:4:5:6:7:8:9:10", dataLoader.getEncoded());

// Additional code

final var dataLoader = new StreamLoader();

assertEquals("1:2:3:4:5:6:7:8:9:10", dataLoader.getEncoded());

More Examples

javax.servlet.GenericServlet.init: Method GenericServlet.init(ServletConfig config) calls the parameterless method GenericServlet.init() which is intended to be overridden in subclasses. Method GenericServlet.init(ServletConfig config) is the template method in this example.

Links
Creating a design identity for a leading distributed ledger services provider
Tags: Branding Strategy, Branding, Identity, Design Process, Design Patterns

The Genesis Block team was seeking a partner who could deliver a new website for them that reflected their ethos of combining the dependability, industry access, and regulatory expertise of providing distributed ledger services with the flexibility, speed, and customer-centricity of a startup.

We developed a distinctive brand identity for Genesis Block which could be applied to both digital and print media, and we worked closely with the client over the course of several iterations to deliver an identity that matched the client’s vision.

The branding and design that we developed have at its heart a polymorphic block — literally a “Genesis Block” — from which distinctive geometric shapes emerge, develop and metamorphose, each representing the services and capabilities that it offers to clients.

We knew that Genesis Block had built an expert advisory and knowledge-sharing network that brings together experts from across financial, strategic, technical, legal, and regulatory domains and to drive customer base expansion, and so we leveraged Webflow’s marketing and customer relationship management tools to ensure that their new site could be effectively managed and updated by the Genesis Block team to help maintain the network and develop new leads.

The Genesis Block rebranding helped to expand the business and company recognition on the industry scene along with bringing new opportunities to its team.
Lesson 21: The Strategy Pattern
By: Andrey Karazhev
Tags: Tutorial, Design Patterns, Strategy Pattern

The pattern belongs to the behavioral category of the design patterns.

Idea

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Explanation

Wikipedia says:

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime.

In plain words:

Using the strategy pattern, it lets the algorithm vary independently from clients that use it.

Class Diagram

The class diagram will be:

Example

The task:

Let’s consider to create an index service that should sort indices by a certain algorithm.

Let’s define a strategy specification:

public interface Strategy {



int[] sort(int[] indices);

}

We need to define an index service:

final class IndexService {

private Strategy strategy;



public IndexService(final Strategy strategy) {

this.strategy = strategy;

}



public void setStrategy(final Strategy strategy) {

this.strategy = strategy;

}



public int[] sort(int[] indices) {

return strategy.sort(indices);

}

}

Let’s create different strategies:

final class BubbleSort implements Strategy {



@Override

public int[] sort(int[] indices) {

int index;

for (var i = 0; i < indices.length; i++) {

for (var j = 0; j < indices.length - 1 - i; j++) {

if (indices[j] > indices[j + 1]) {

index = indices[j];

indices[j] = indices[j + 1];

indices[j + 1] = index;

}

}

}



return indices;

}

} final class InsertionSort implements Strategy {



@Override

public int[] sort(int[] indices) {

int j, index;

for (var i = 1; i < indices.length; i++) {

index = indices[i];

for (j = i; j > 0 && indices[j - 1] > index; j--) {

indices[j] = indices[j - 1];

}



indices[j] = index;

}



return indices;

}

}

And then it can be used as:

var i = 0;

final var service = new IndexService(new BubbleSort());

for (final var index : service.sort(new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1})) {

assertEquals(++i, index);

}

// Additional code

var i = 0;

final var service = new IndexService(new InsertionSort());

for (final var index : service.sort(new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1})) {

assertEquals(++i, index);

}

More Examples

Links
Transfer Object Pattern
By: Daniel Liu
Tags: Java Design Pattern, Java, Design Patterns, Programming, Backend Development

Overview

The main use of the Transfer Object Pattern is to pass data with multiple attributes at once. It is made up of 3 parts:

Transfer Object — Simple Plain Old Java Object(POJO) which just has getters and setters

Business Object — Contains the logic that manipulates the transfer object.

Client — Passes or gets transfer object from the business object

Photo by Markus Winkler on Unsplash

Implementation

Transfer Object

PersonTO.java

public class PersonTO {

private String name;

private int id;



PersonTO(String name, int id){

this.name = name;

this.id = id

}



public String getName() {

return name;

}



public void setName(String name) {

this.name = name;

} public String getId() {

return id;

}



public void setId(String id) {

this.id = id;

}

}

Business Object

PersonBO.java

import java.util.ArrayList;

import java.util.List;



public class PersonBO {

// database

List<PersonTO> people;



public PersonBO(){

people = new ArrayList<PersonTO>();

PersonTO p1 = new PersonTO("Gary", 0);

PersonTO p2 = new PersonTO("Sam", 1);

people.add(p1);

people.add(p2);

}

public void deletePerson(PersonTO person) {

people.remove(person.getId());

System.out.println(person.getId() + ". " + person.getName() + " deleted");

}



public List<PersonTO> getAllPeople() {

return people;

}



public PersonTO getPerson(int id) {

return people.get(id);

}



public void updatePerson(PersonTO person) {

people.get(person.getId()).setName(person.getName());

System.out.println("Id " + person.getId() + " updated");

}

}

Client

Demo.java

public class Demo {

public static void main(String[] args) {

PersonBO personBusinessObject = new PersonBO(); // Print all people

for (PersonTO person : personBusinessObject.getAllPeople()) {

System.out.println("Id : " + person.getId() + ", Name : " + person.getName());

}



// Update person

PersonTO person = personBusinessObject.getAllPeople().get(0);

person.setName("Jim");

personBusinessObject.updatePerson(person);



// Get person

person = personBusinessObject.getPerson(0);

System.out.println("Id : " + person.getId() + ", Name : " + person.getName());

}

} >> Id: 0, Name: Gary

>> Id: 1, Name: Same

>> Id 0 updated

>> Id: 0, Name: Jim

Conclusion

Using Data Transfer Pattern you can group multiple calls together. In the example above it retrieves, update and deletes. However, it is not only limited to those actions. This pattern should be used if the client requests multiple information and they are related, increase performance to retrieve resources and you want to reduce the number of calls.
從 Arel 看 Visitor Pattern
By: Shih-Ying Chen
Tags: Design Patterns, Rails

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Lesson 20: The State Pattern
By: Andrey Karazhev
Tags: Tutorial, Design Patterns, State Pattern

The pattern belongs to the behavioral category of the design patterns.

Idea

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Explanation

Wikipedia says:

The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes.

In plain words:

With the state pattern, it’s possible for an object to change its behavior at runtime without resorting to conditional statements and thus improve maintainability.

Class Diagram

The class diagram will be:

Example

The task:

Let’s consider to create a context that can change its states based on executed commands.

Let’s define a state specification:

public interface State {



void execute(final Context context, final String command);

}

We need to define a context:

final class Context {

private State state;



public Context() {

state = new Offline();

}



void setState(final State state) {

this.state = state;

}



String getState() {

return state.getClass().getSimpleName();

}



public void execute(final String command) {

state.execute(this, command);

}

}

Let’s create different states (i.e. online, offline, Paused):

final class Online implements State {



@Override

public void execute(final Context context, final String command) {

if ("pause".equals(command)) {

context.setState(new Paused());

} else if ("stop".equals(command)) {

context.setState(new Offline());

}

}

} final class Offline implements State {



@Override

public void execute(final Context context, final String command) {

if ("start".equals(command)) {

context.setState(new Online());

}

}

} public class Paused implements State {



@Override

public void execute(final Context context, final String command) {

if ("start".equals(command)) {

context.setState(new Online());

} else if ("stop".equals(command)) {

context.setState(new Offline());

}

}

}

And then it can be used as:

final var context = new Context();

assertEquals("Offline", context.getState());

context.execute("start");

assertEquals("Online", context.getState());

context.execute("pause");

assertEquals("Paused", context.getState());

context.execute("stop");

assertEquals("Offline", context.getState());

More Examples

Links
Patrón de Fábrica— Crea objetos de manera extendible [Factory Pattern]
Tags: Typescript, Software Development, Design Patterns, Español, Factory Pattern

calvinespinoza/factory-pattern

GitHub is home to over 50 million developers working together to host and review code, manage projects, and build…
Lesson 19: The Observer Pattern
By: Andrey Karazhev
Tags: Tutorial, Observer Pattern, Design Patterns

The pattern belongs to the behavioral category of the design patterns.

Idea

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Explanation

Wikipedia says:

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

In plain words:

With the observer pattern, it’s possible to provide communications between objects with event handling.

Class Diagram

The class diagram will be:

Example

The task:

Let’s consider to create a source that generates events and a dispatcher should buffer them.

Let’s define an observer:

interface Observer<T> {



void update(final T data);

}

We need to define an observable specification:

interface Observable<T> {



void registerObserver(final Observer<T> o);



void removeObserver(final Observer<T> o);



void notifyObservers();

}

Let’s create an event source:

final class Events implements Observable<String> {

private final List<String> events = new LinkedList<>();

private final List<Observer<String>> observers = new LinkedList<>();



@Override

public void registerObserver(final Observer<String> o) {

observers.add(o);

}



@Override

public void removeObserver(final Observer<String> o) {

observers.remove(o);

}



@Override

public void notifyObservers() {

observers.forEach(observer -> {

for (final var event : events) {

observer.update(event);

}

});

}



public void generate() {

IntStream.range(0, 5).forEach(value -> events.add("Event_" + value));

notifyObservers();

}

}

And a dispatcher will be:

final class Dispatcher implements Observer<String> {

private final List<String> data = new LinkedList<>();



@Override

public void update(final String data) {

this.data.add(data);

}



public String getBuffer() {

final var buffer = new StringBuilder();

data.forEach(string -> buffer.append(string).append(":"));

buffer.deleteCharAt(buffer.length() - 1);

buffer.trimToSize();

return buffer.toString();

}

}

And then it can be used as:

final var dispatcher = new Dispatcher();

final var events = new Events();

events.registerObserver(dispatcher);

events.generate();

events.removeObserver(dispatcher);



assertEquals("Event_0:Event_1:Event_2:Event_3:Event_4", dispatcher.getBuffer());

More Examples

Links
Designer sneakers you will love
By: Black Square Design
Tags: Designer, Design Patterns, Design, Design Process, Design Thinking

write in the comments which design do you like

All this can be found here https://www.zazzle.com/store/vagrantstore
Domain Driven Design and Pattern Thinking
By: Anes Hasicic
Tags: Design Patterns, Ddd

Design patterns are very useful things in general and they pop up a lot if you are applying DDD in an OOP context (If you’re there you are probably already applying Tactical DDD patterns).

One principle I want to emphasize here because I see so many violations of it, is the following: “Don’t use pattern names when implementing a pattern”.

It’s amazing how people keep missing the point.

Applying this principle is actually very helpful in double checking if you are applying the right pattern to the right thing. What do I mean?

If you are finding it hard not to add that Strategy, Builder, State, Specification postfix or prefix to your pattern implementation, that might be a good sign that you were guided by the patterns-first approach, instead of domain-first and that there is a good chance that you have misunderstood an important domain concept in eagerness to employ a specific design pattern.

(This does not only apply to DDD, it’s a good practice in general)

Pattern names should be invisible in your codebase, and they should be replaced with domain concepts instead.

Patterns provide solutions for “classes” of problems that are applicable in “different contexts”.

Context is the king! but still, context is so often disregarded and we jump straight to implementation without understanding in which context we are operating.

The reality is that everything depends on the context.

“That” is the reason why patterns have those generic names that they have: Singleton, Builder, Factory, State, etc…

The basic premise when using patterns is not to force them. Let them present themselves in your particular context, which will, in turn, reflects to the names also.

A pattern must have meaning inside of your domain. For example:

Instead of XXXStrategy, an XXXPolicy might be more appropriate (or maybe you don’t even need the suffix)

Instead of XXXState, use a domain concept such as ClosedAccount, ActiveAccount, etc…

Pattern thinking heavily influenced Domain Driven Design (and yes Eric put patterns to context and didn’t use “Pattern” in the title — He called it Domain Driven Design)
팝업의 타이밍: 인터랙션 중이거나 중요한 과업 중에는 보여주지 말아라.
By: Byeongjun Kim
Tags: Design Patterns, Web Usability, UX Design

[번역] 팝업: 10가지 문제 동향과 대안

This article is a translation of Anna Kaley’s article: Popups: 10 Problematic Trends and Alternatives. All rights belong to the authors of the original article.
Lesson 16: The Iterator Pattern
By: Andrey Karazhev
Tags: Tutorial, Design Patterns, Iterator Pattern

The pattern belongs to the behavioral category of the design patterns.

Idea

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Explanation

Wikipedia says:

In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container’s elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.

In plain words:

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Class Diagram

The class diagram will be:

Example

The task:

Let’s extend configs class by adding implementation for the iteration logic.

Let’s implement the iterator interface:

public final class Configs implements Config, Iterator<Config> {

private int position = 0;

private final List<Config> configs = new LinkedList<>();



public void add(final Config config) {

configs.add(config);

}



public void remove(final Config config) {

configs.remove(config);

}



@Override

public int getId() {

int value = 0;

for (final var config : configs) {

value += config.getId();

}



return value;

}



@Override

public String getName() {

final var name = new StringBuilder();

for (final var config : configs) {

name.append(config.getName()).append(";");

}



name.deleteCharAt(name.indexOf(";"));

return name.toString();

}



@Override

public boolean hasNext() {

return position < configs.size() - 1;

}



@Override

public Config next() {

if (!hasNext()) {

throw new NoSuchElementException();

}



return configs.get(position++);

}

}

And then it can be used as:

final var configs = new Configs();

configs.add(new UserConfig(1001, "Name 1"));

configs.add(new UserConfig(1002, "Name 2"));

configs.add(new UserConfig(1003, "Name 3"));



var position = 1;

while (configs.hasNext()) {

final var config = configs.next();

assertEquals(1000 + position, config.getId());

assertEquals("Name " + position, config.getName());

position++;

}

More Examples

Links
Startup a boncasztalon
By: Fülig Jimmy
Tags: Cancer, Startup

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
We didn’t have turkey for Christmas lunch but were inspired by Turkey instead.
By: Mark Davies
Tags: Cancer, Turkey, Christmas, Chemotherapy, Myeloma

We didn’t have turkey for Christmas lunch but were inspired by Turkey instead. It took some doing on my part to dispense with tradition and instead have a feast of lamb, merguez, hummous and salads drawn from Turkish, Lebanese and Moroccan cuisine, but it was a very good move.

And after all it was a Christmas like no other. For everyone, of course, but with added extras in our house. Some things were familiar – assembling my son’s present at 3am on Christmas Day wasn’t a first – others less so. Starting the morning with a dog walk was new, as was then coming home and injecting myself with the drugs which marked the beginning of the third cycle of chemotherapy as I battle myeloma.

It was a good day to be starting a new round. I also take steroids to once a week and they provide an energy boost (and as I may have mentioned, hiccups) which was perfectly timed to allow for a lovely Christmas Day with the family, and hopefully a decent weekend – after three days I tend to slump into a sleepy torpor for 48 hours. But I’m not thinking about that right now.

There are some benefits to cancer though. It provides ample scope for clearer thinking, and a shedding of unnecessary distractions. I’d previously have fretted about not having turkey on Christmas Day, having always been a stickler for traditions of all kinds. I feel now like I don’t have time for stuff like that – I just want to enjoy every day as much as possible. The meal was unbelievably good (its preparation being nothing to do with me). And I’m not sure I really like turkey anyway.

This sense of being freed from such baggage stretches beyond Christmas too. I’m less inclined to fret about little things, much more focused on the present and take so much joy from simple things like a walk through the mud of Keston Common, or napping with the dog doing the same while stretched out on my shoulder. These are life’s richest joys.

So while it was different it may just be that this Christmas Day was one of the most wonderful I’ve enjoyed. Cancer didn’t hang over it because we didn’t let it, just as we put Covid as far from our minds as we could. We zoomed happily with grandparents of course, and we are all getting rather good at making the best of that.

It’s the grounding I think that an illness like this provides. It knocks the edges off. I’m not always going to be as upbeat as this, but I am learning about life and the cancer helps with that. I’m not going to say I am grateful to it, but I will definitely take what wins I can find.
A High-Fat Diet Starves Immune Cells, Tumor Growth Goes Unchecked
By: Tara Fernandez
Tags: Health, Cancer, Diet, Immunology, Obesity

Sitting down to enjoy an indulgent Christmas feast? A recent study in mice by Harvard Medicine scientists found that a diet high in saturated fat can stunt immune cells, allowing cancer cells to run rampant. The fatty diet also triggers tumor cells to tweak their metabolisms, allowing them to be fueled by fat instead of sugar. This further supports their uncontrolled growth in the absence of immune push-back.

In the study, led by cell biologist Marcia Haigis and published in the journal Cell, the research team provided new insights on the impact of diet on cancer immunity. Specifically, they found a sharp decline in the presence of cytotoxic CD8+ T lymphocytes within tumors. These white blood cells play a key role in antitumor immunity via their capacity to recognize and kill malignant cells.

However, a diet high in fat cripples the ability of these immune cells to fight back against tumors. The authors managed to unravel the mechanism behind this phenomenon: tumor cells rewire their metabolisms to take full advantage of the abundance of fat (an energy-rich fuel source), which allows them to flourish, leaving “starving” T cells in their tracks.

“Putting the same tumor in obese and nonobese settings reveals that cancer cells rewire their metabolism in response to a high-fat diet,” explained Haigis

“This finding suggests that a therapy that would potentially work in one setting might not be as effective in another, which needs to be better understood given the obesity epidemic in our society.”

Interestingly, while high-fat diets caused CD8+ cell numbers to dwindle inside tumors, this observation was not noted in other parts of the body. Inside the tumors, the team found that T cells were sluggish with extremely impaired functionality. However, once extracted and relocated to cell culture dishes, they bounced back, with immune activity normals returning to baseline. Clearly, an essential fuel source was not available to these immune cells within the context of the tumor microenvironment.

The good news is that there is a way to stop tumor cells from rewiring their metabolisms using pharmaceutical interventions.

“Cancer immunotherapies are making an enormous impact on patients’ lives, but they do not benefit everyone,” said a senior author of the study, Arlene Sharpe.

We now know there is a metabolic tug-of-war between T cells and tumor cells that changes with obesity, says Sharpe.

“Our study provides a roadmap to explore this interplay, which can help us to start thinking about cancer immunotherapies and combination therapies in new ways.”

“Our study provides a high-resolution metabolic atlas to mine for insights into obesity, tumor immunity, and the crosstalk and competition between immune and tumor cells. There are likely many other cell types involved and many more pathways to be explored,” added Haigis.
A Special Thank You To My Mask
By: S. G. S. Abel
Tags: Cancer, Health And Wellness, Blessings, Life Lessons, Sun

A Special Thank You To My Mask

Photo by Paul Siewert on Unsplash

This week I have been happy to don my mask before going into public. You see, it’s that time of year. The annual visit to the dermatologist.

So not only has my mask been protecting me from COVID, it’s been covering 3 scabs from having precancerous spots frozen off my face.

It’s not so much my vanity coming out. I’m not a makeup wearer. I do look my age. But come on, scabs?

This is at least an annual event when your my age. Born before the invention of modern day sunscreen, as a teenager it was baby oil, QT (Quick Tan, for you youngsters) or zinc oxide. And I was vain as a teenager. QT would turn you (and your clothes) orange and zinc oxide is, well, zinc oxide. I spent the first half of my summer slathered in baby oil and the second half marked with the white war paint of zinc oxide across my face. Now I currently have scabs for a week.

So thank you mask, for being a multipurpose accessory. And for anyone who may be reading- wear sunscreen! Your lack of tan lines is sexier than scabs, or the alternative.
Is Beetroot Useful in Preventing Cancer? — Daily Life Hacks
Tags: Cancer, Juice, Beetroot, Immune System, Vegetables

There are many benefits to using vegetables. Each vegetable has a unique benefit that is rich in nutrients, vitamins, and proteins, etc. Today we will talk about beetroot which has a special shape in appearance. Experts call beetroot an excellent vegetable for protecting human health. Eating it protects against many diseases and strengthens the immune system.

According to the Egyptian website Al-Akhbar el-Yom, research has shown that beetroot is good for the kidneys and that it removes fat and toxins from the liver. It also prevents respiratory problems and keeps the digestive system healthy.

Read more articles about health and fitness here: Daily Life Hacks

Beetroot is rich in antioxidants, it improves digestion and removes fat from the body. It protects the eyes from cataracts, strengthens the immune system, prevents respiratory problems, protects the skin, and improves blood circulation. Research has shown that beetroot is very helpful in preventing cancer because it contains beta carotene. Therefore, experts recommend drinking a cup of beetroot juice daily.

Beetroot juice reduces anemia and regenerates blood cells with a large amount of iron because its juice is rich in flavonoids and beta carotene and helps to eliminate body fat and helps to clear the liver.

Beetroot juice increases the body’s ability to function. Nutritionists recommend that daily use of it helps to reduce lethargy and activate the body.

Support Me:

If you are looking for better and effective herbal weight loss products then please buy from here, I can give you access to the products of Zotrim and other well known and good companies.

Click here to buy Zotrim’s herbal weight loss products at a reasonable price.
Best Cancer Specialist Doctor in Delhi | Dr. Dodul Modal
By: Dr Dodul Mondal
Tags: Cancer, Best Cancer Hospital

Dr Dodul Mondal is one of the most prominent and dynamic radiation oncologists of India with international repute who has an experience of working.
Cancer Treatment Needs a Fundamental Change
By: Mukundarajan V N
Tags: Health, Cancer, Cancer Cure Medicine, Research, Cancer Prevention

Cancer Treatment Needs a Fundamental Change

Photo by National Cancer Institute on Unsplash

With minor variations, a protocol of surgery, chemotherapy, and radiation — the slash -burn-poison approach to treating cancer — remains unchanged. It is an embarrassment. Equally embarrassing is the arrogant denial of that embarrassment.(Azra Raza, Oncologist)

Prevention is better than cure is an axiom that everybody seems to accept as a sensible way of life except the practitioners of modern medicine. Rigid treatment protocols have hijacked the medical profession.

There is a joke that fewer people died because of complicated heart surgeries during the annual meeting of cardiologists. Surgeons do procedures like angioplasty as a matter of routine even if patients do not have any life-threatening conditions.

It is very difficult to get new ideas into medicine. They cast the philosophy of modern medicine in stone: there are no nuances, no possibility to question conventional wisdom except with witch-hunting and loss of medical licence, no space to think independently, and no margin to try alternatives to rigid procedures.

Cancer treatment is a typical case of rigid and complacent thinking that likes to tom-tom progress where there is little to celebrate. It is painful to admit that we are not winning the so-called war on cancer.
Is Cancer Really That Hard To Treat?
By: Shubham Thakur
Tags: Health, Diseases Treatment, Cancer, Disease

The disease is truly difficult to treat, however the inquiry is, the reason? This is a direct result of numerous components and incorporates numerous illnesses. In this way, to put it plainly, malignancy treatment is so difficult in view of the presence of so numerous basic gatherings of sicknesses.

Indeed there are numerous sorts of diseases, and many keep on getting found. In excess of 100 assortments have been revealed as of not long ago, which is a serious enormous number. The disease has no fixed reason, no fixed treatment, and no fixed side effects. It tends to be caused because of some outside factor or can create from a sickness causing life form inside.

Components influencing malignant growth treatment: