I am a professional Graphics Designer. I will serve not only as a career growth but also challenge to my profession and service to the best of my ability. My goal is to professional and high-quality design for client's satisfaction.
Thank you!!!
I am a professional Graphics Designer. I will serve not only as a career growth but also challenge to my profession and service to the best of my ability. My goal is to professional and high-quality design for client's satisfaction.
Thank you!!!
I have a class called PhotoManager
it's a singleton. This class contains methods like:
fun downloadPhoto(context: Context, photoUrl: String) { }
fun savePhotoUri(context: Context, uri: Uri) { }
fun setWallpaper(context: Context, photoUri: Uri) { }
I also have some other classes that have Manager
postfix in their names. For example, SuggestionManager
that receives some input data and returns user-based suggestions.
I'd like to refactor these two classes but I don't know which pattern to use. Can it be the Facade pattern? Thank you.
The following code exemplifies the initial situation on which I want to improve:
# expensive function execution returning a value
def f(x:int):
print(x)
return 2*x
# the value is to be stored globally
gvar = f(3)
# this function uses the global variable
def g():
print(gvar)
First of all I don't want gvar
to be set immediately but upon the first time it is used (lazy loading):
gvar = None
def g():
gvar = f(3)
print(gvar)
But also I don't want gvar
to be set every time it is used as well:
gvar = None
def g():
if gvar is None:
gvar = f(3)
print(gvar)
And finally I want this to happen as transparently as possible - the result should be something similar to this:
gvar = magic(f, 3)
def g():
print(gvar)
So I can just use gvar
as if it was a normal variable while it actually invisibly encapsulates a mechanism that will lazy load its value.
Is that possible?
To give you further context. The practical scenario is a FastApi service where g()
would represent a path. Several of those endpoints might use the same global variable which should only be used once. To make the pattern more reusable and pluggable I would like the lazy loading to happen transparently.
I'm quite new at design patterns, and I want to understand, if there is a 'tree of responsibility' design pattern, as a variation of 'chain of responsibility'?
I've been reading about FactoryPatterns and now i'm trying to grasp the idea, which implementation is best practice.
I guess there are a couple of options:
Factory factory = new Factory(); Obj obj = factory.createObj(TYPE);
Question 1: Do you really instantiate it everywere in the code?
Question 2: I've read in blogs and forums that the new operator is considered harmful. Isn't it the same for instantiating the Factory itself?
My preferred option, creating a static method inside my factory
public class Factory { public static void createObj(TYPE){ .. }}
Question 3: Due to the static method, am i shooting myself in my foot later on because the static method can't be overriden/adjusted in runtime?
I think this questions come closest to mine, and there are some good points in it. But i'd like to discuss it more.
Why should the getInstance() method in Factory pattern be static?
Factory Creation Methods Always Static?
I want to make matrix 512 columns x 256 rows, with the pattern like this as:
I was trying it with this one:
$b = 0;
matrik = [[]];
for ($i=0; $i < 512; $i++) {
for ($j=0; $j < 256; $j++) {
if ($j=$b) {
$matrik[$j][$j] = 1;
}else{
$matrik[$j][$j] = 0;
}
$b++;
}
}
return $matrik;
but output of this code was:
[
[
0
],
{
1: 1
},
{
2: 1
},
{
3: 1
},
{
4: 1
},
{
5: 1
},
I know there is not a good idea to instantiate a class variable from a method but unfortunately, I face a situation where I do not have any other solution. I have created some custom validators and I have an object (rawField
) that is populated with some information from GUI. To populate that instance variable I use the method validate from javax.faces.Validator
.
So I get the information for each field from GUI through this event.
My question is: Is this a good design pattern? Has anybody a better idea about how should I instantiate this variable?
Parent class:
public abstract class FormFieldValidator extends BaseValidator implements IFormFieldValidator, Validator {
protected RawField rawField;
@Override
public abstract RawField doInitialize(Object inputObject);
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
rawField = doInitialize(value);
if (rawField == null) {
throw new IllegalArgumentException("The field cannot be empty");
}
doBasicValidation();
}
}
Child class
@FacesValidator(Constants.Validators.USERNAME_VALIDATOR)
public class UsernameValidator extends FormFieldValidator {
@Override
public RawField doInitialize(Object guiField) {
ValidationConditions validationConditions = new ValidationConditions
.Builder(Entities.ParamsSize.USERNAME_MIN_LENGTH, Entities.ParamsSize.USERNAME_MAX_LENGTH)
.setRegex(Constants.Regex.USERNAME_REGEX).setNullable(false).setUnique(true).build();
FieldDetails fieldDetails = new FieldDetails(guiField, "Username");
RawField rawField = new RawField(fieldDetails, validationConditions);
return rawField;
}
}
I am trying to create a simple factory pattern. Below is my sample code:
IMobile:
namespace SimpleFactory
{
public interface IMobile
{
}
}
IPhone:
namespace SimpleFactory
{
public class Iphone : IMobile
{
public void Hello()
{
Console.WriteLine("Hello, I am Iphone!");
}
}
}
Nokia
namespace SimpleFactory
{
public class Nokia : IMobile
{
public void Hello()
{
Console.WriteLine("Hello, I am Nokia!");
}
}
}
MobileFactory:
namespace SimpleFactory
{
public class MobileFactory
{
public IMobile GetMobile(string mobileType)
{
switch (mobileType)
{
case "Nokia":
return new Nokia();
case "iPhone":
return new Iphone();
default:
throw new NotImplementedException();
}
}
}
}
Program:
namespace SimpleFactory
{
class Program
{
static void Main(string[] args)
{
MobileFactory factory = new MobileFactory();
IMobile mobile = factory.GetMobile("Nokia");
mobile.Hello(); // Not able to access Hello method of Nokia class.
}
}
}
I would like to access Hello method of the Nokia and Iphone. Can I access Hello method of the Nokia or Iphone class. If not, why? (I can add this Hello method to the Interface and able to access it. But my question is How I can access class own methods? )
is there any way to create objects for the same model which is calling again and again. Or any best practice even design pattern. Note- Cannot take map
Example-
**MothlyData** mdapril = dao.getData("April");
**MothlyData** mdmay = dao.getData("May");
**MothlyData** mdjune = dao.getData("June");
**MothlyData** mdajuly = dao.getData("July");
**MothlyData** mdaaug = dao.getData("Aug");
**MothlyData** mdasept = dao.getData("Sept");
Once my program starts running it is not stopping after few steps . can anyone help me with this
void main()
{
int n,row,column,lim1,lim2,k;
scanf("%d",&n);
lim2=(2*n)-1;
lim1=1;
k=n;
for(row=1,column=1;row<=lim2,column<=lim2;row++,column++)
while((row||column=lim1)||(row||column=lim2))
{ printf("%d",k);
n--;
lim1=lim1+1;
}
}```
Often I need to have function/method return different number OR types of values.
def test(x,y,ret='both') :
s = x + y
m = x * y
if ret = 'both' : return s, m
if ret = 'sum' : return s
if ret = 'mult' : return m
Also sometimes I want to have Aspect type behavior where I inject debugging code, which may also change the return types/num-of-vals
Is there a standard Programming pattern that handle this ? Decorators ?
The example work but is abit clunky..
I'm not sure the question accurately reflects my dilemma. The Film
instances are not actually linked in the chain of the parent `Director' MRO, since they do not inherit from that class.
There are a lot of problems with this, not the least of which, as I investigate, how to refactor this for use with SQLAlchemy. Simple standard library (3.7) dataclass
declarative
are easy to construct, and work well, even with and as mixins, but the wangly bits of associative relationships in Python classes, as presented here, remain, for me, largely a mystery with what looks like a barely reachable horizon.
On the way to this sunrise, the biggest problem here, aside from positioning the classes for refactoring for use with SQLAlchemy, is assigning a Director
instance id
, to each of the films.
If you have some insight on ordering output, that would be great. As it is, order is persevered according to declaration order in the class, but it is scuttled by the fact any attribute with a default value must not precede any which are auto initialized, meaning order counts in the declaration according to how a value is obtained.
Sorry if this is a bit dirty. This is fresh from notes and no effort was made to reduce it down.
Any other questions/answers you can throw at it with respect to standalone refactoring optimization, and in the theoretical SQLAlchemy context, all very much appreciated. I'll do what I can to edit this if there is interest in chipping away at best practices here.
On an additional side note, I had some trouble importing InitVar
. As I'm using Python 3.6.9
, and dataclasses
is installed via pip install dataclasses
, I'm wondering if that is a known problem solved with standard library adoption in Python 3.7
, or likely something unique to my end?
As I continue to work on this I'm looking for pointers on how to deal with dates. Notice the birth date of the directors here, hanging around as comments. There is no dataclass type for date
, and, if I'm not mistaken, Any
from the typing
library, the same one List
, with a capital 'L' comes from, would facilitate auto initialization, requiring entry on instancing a class. To that end, calculating the age from an entered birth date is also desired.
Imports
from dataclasses import dataclass, field, asdict, astuple
from typing import ClassVar, List, Any
import pprint
from pprint import PrettyPrinter
pp = pprint.PrettyPrinter(indent=4)
@dataclass
class Film:
_films_count: ClassVar = 0
_films_list: ClassVar = []
name: str
year: str
director_id: int = field(default_factory = int, init=False)
# film_list: list = field(default_factory = list)
film_tuple: tuple = field(default_factory = tuple)
id: int = field(init=False)
def __post_init__(self):
# director_id = Director.id
Film._films_count += 1
self.id = Film._films_count
# d_films = Films()
# d_films = Film("Lucy", 2016)
# print(d_films)
# print(asdict(d_films))
@dataclass
class Director:
_director_count: ClassVar = 0
_director_names: ClassVar = []
firstname: str
lastname: str
age: int
fullname: str = field(init=False)
film_list: List[Film] # = field(default_factory=list)
id: int = field(init=False)
def __post_init__(self):
# pass
Director._director_count += 1
self.id = Director._director_count
self.fullname = f"{self.firstname} {self.lastname}"
Director._director_names.append(self.getfullname())
Director._director_names.append(self.fullname)
def getfullname(self):
return self.fullname
@classmethod
def assign_id(cls):
print("Class ", cls)
return Director._director_count + 1
d_assign_id = Director.assign_id()
print("D_ID ",d_assign_id)
films = (Film("Lucy", 2014, d_assign_id), Film("5th Element", 1997, d_assign_id), Film("Anna", 2019, d_assign_id))
d = Director("Luc", "Besson", 60, films)
# March 18, 1959
d_assign_id = Director.assign_id()
films = (Film("Star Trek: Into Darkness", 2013, d_assign_id), Film("Mission Impossible III", 2006, d_assign_id), Film("Star Wars: The Force Awakens", 2015, d_assign_id))
e = Director("JJ", "Abrams", 53, films)
# June 27, 1966
print(d.getfullname())
print(d.__repr__())
print(Director._director_count)
dashed()
print(Director._director_names)
dashed()
for _ in Director._director_names:
print(_)
dashed()
pp.pprint(asdict(d))
dashed()
# pp.pprint(astuple(d))
# dashed()
# pp.print(Film._film_names[:])
pp.pprint(asdict(e))
Output
d_assign_id
does not work. In film_list.director_id
, for each entry, the value remains 0
. How would you approach refactoring this so that it works? How would you describe the relationship between the classes, in OO parlance and, hopefully, table metadata lingo?
☂ # ☂ # ☂ # ☂ # ☂ # ☂ # ☂ # ☂ # ☂ # ☂
{ 'age': 60,
'film_list': ( { 'director_id': 0,
'film_tuple': 1,
'id': 1,
'name': 'Lucy',
'year': 2014},
{ 'director_id': 0,
'film_tuple': 1,
'id': 2,
'name': '5th Element',
'year': 1997},
{ 'director_id': 0,
'film_tuple': 1,
'id': 3,
'name': 'Anna',
'year': 2019}),
'firstname': 'Luc',
'fullname': 'Luc Besson',
'id': 1,
'lastname': 'Besson'}
☂ # ☂ # ☂ # ☂ # ☂ # ☂ # ☂ # ☂ # ☂ # ☂
{ 'age': 53,
'film_list': ( { 'director_id': 0,
'film_tuple': 2,
'id': 4,
'name': 'Star Trek: Into Darkness',
'year': 2013},
{ 'director_id': 0,
'film_tuple': 2,
'id': 5,
'name': 'Mission Impossible III',
'year': 2006},
{ 'director_id': 0,
'film_tuple': 2,
'id': 6,
'name': 'Star Wars: The Force Awakens',
'year': 2015}),
'firstname': 'JJ',
'fullname': 'JJ Abrams',
'id': 2,
'lastname': 'Abrams'}
☂ # ☂ # ☂ # ☂ # ☂ # ☂ # ☂ # ☂ # ☂ # ☂
I am a ruby on rails developer. I want to learn design patterns. Which all design patterns should I consider learning and from where to start? Please suggest some sources to refer.
How do I extend WPF application from running one in a simple form? In other words, how to make WPF app builder? What to learn (except WPF tutorials XD)? Focus or even read? …thanks in advance every word will help?
i want to Write a function: sequential_research (M, L) for example, which, using the principle of research sequential in the list of suffixes L, returns the position of the first tuple, such that M is a prefix of suffix of this tuple, if it exists; otherwise, the function returns None.
I am new to designing softwares, and I am trying to build a Tree like struct.
I have an empty interface like this:
interface Node{
}
Two classes NodeA
and NodeB
implement this interface, and both have some specific attributes. Except that these are Nodes, they dont have anything common in them.
class A implements Node {
public String a;
public A(String a){
this.a = a;
}
}
class B implements Node {
public int a = 5;
public String z = "xyz";
public B(int a,String z){
this.a = a;
this.z = z;
}
}
I have a a class Parse
that creates instances of the above classes , depending on certain conditions.
class Parse {
List<Boolean> l;
private static int i=0;
Parse(List<Boolean> l){
this.l = l;
}
private Node parseA() {
return new A(/* param */); // Assume some parameters here
}
private Node parseB() {
return new B(/* param */); // Assume some parameters here
}
private boolean getNextState(){
return l.get(i++);
}
public Node parse(){
boolean x = getNextState();
if(x){
return parseA();
}
else{
return parseB();
}
}
}
Driver class:
public class Test {
public static void main(String[] args) {
List<Boolean> l = Arrays.asList(true,false); // so on...
Parse p = new Parse(l);
Node b = p.parse(); // not sure if its NodeA or NodeB
}
}
After building the tree, i am planning to use visitor pattern to retrieve some attributes and do some operations.
So at last, when i get a
Node b
, i want to access its attributes (ofNodeA
orNodeB
), which i know cant be done as Polymorphism doesnt work that way.
I think that using instanceof
ladder and type-casting arent proper solutions to it.
Sorry for this silly problem, but being new to designing, i aint getting what to do next.
How shall one solve this design problem? can anyone share a small design structure for this, assuming that this structure will grow bigger and have ample of different nodes. [may be Java Generics
help here]
Note: chaning above design is fine,but if possible, a small sample code is appreciated.
I have 2 classes: Box and Apple.
A Box contains Apples. An apple can only ever belong to one box. An apple must belong to a box. Each apple has a position in the box. This could be managed either by Apple or by Box. An apple also contains a bunch of other properties not relevant to Box. An apple can be moved from one box to another.
But how can I enforce the constraints above?
The only idea I have is that a box keeps track of the position of an apple and also have a static dictionary mapping an apple to a board, but this seems like not good design?
I am working in an android project which have factory class polluted with too many object creation. Basically, we have more than 10 classes in our application and initialise all objects inside a single factory class. This will be used by any class in an application to access required object. Eg: factory.getObjectX. Currently, this factory holds 12 member variable objects and it is creating ~18 objects. So, it kills readability. This class would grow further in the future and it is already bloated up.
Another issue is that we are using dependency injection. So, this factory creates all required objects of classA and then initialise classA which explains ~18 object creation and 12 member variables I mentioned above. I don't think we need dependency injection here because objects required for classA are within the scope of it and also, not used by any other class in the application. When I want to create new object in classA tomorrow, then factory class and classA would be disturbed which violates SRP and open closed principle.
Two questions,
1.I am more interested in dependency injection(2nd) problem. Do I need dependency injection in this situation? When should I use dependency injection generally? My understanding is that if a same object is required in multiple classes then it can be injected.Also, if a class have to act upon different variants of an object then it can be created outside and injected.
2.I am open to solve first problem(single factory with all object creation) also.
Please share your thoughts and suggestions.
I'm writting a simulator that could make use of a number of libraries for a card game with different pros and cons. The libraries have similair concepts(e.g. they all know about a card) which allows me to write mostly a single structure of code and swap in the various libaries. My problem is that the entities in the libraries differ slightly and obivous the only common ancestor across the two libraries is object. Is there a standard approach to this problem?
I have a list of 9 million mobile numbers where I need to identify fancy/VIP mobile numbers anybody can help how to do that
I am working on a Java project and I would like to a really clean "Object Oriented" design (the best I can...).
But I am struggling to understand how each object should reference the others.
Let's take the simple standard chess game example :
In my application, I will probably need to be able to retrieve the information in both way :
Here are my questions :
I do not like the X-ref solution, because it basically duplicate the information and it can potentially create inconsistency and a lot of work overload. But can it be avoided ?
I know those questions are a bit fuzzy but I do not think I can figure out alone ! Please help !
Thanks anyone.
I have been searching for factory method without memory allocation and I have not found anything yet.
I want to make an inheritance tree like this:
Controller_Base_Class
| |
Specific_Class1 Specific_Class2 ...
In all factory methods that I've seen the helper class that creates the actual specific class, allocates memory with new and returns the object. For some reasons I would like to do it without new memory allocation.
Having that there won't be much Specific classes, would it make sense that the helper class had a reference of every Specific class and returns the one I need? Something like:
class BaseClass
{
whatever
}
class Specific1 : public BaseClass
{
whatever
}
class Specific2 : public BaseClass
{
whatever
}
class Factory
{
public:
Factory();
BaseClass* Create(SpecType type);
private:
Specific1 specific1;
Specific2 specific2;
}
Factory::Factory() : specific1(), specific2()
{
}
BaseClass* Factory::Create(SpecType type)
{
if(type==SpecType1)
{
return &specific1;
}
...
}
...
//function where i want to do it
Factory factory = Factory()
BaseClass* inheritance_holder = factory.Create(Spec1Type);
...
Sample 1
@Component(policy = ConfigurationPolicy.OPTIONAL, immediate = false)
public class ServiceImpl implement Service {
@Override
public void foo() {
}
...
}
Sample 2
@Component(policy = ConfigurationPolicy.OPTIONAL, immediate = false)
public class Service {
public void foo() {
}
...
}
I have a component which consists some methods. I want to provide a ServiceImpl class which implement Service interface as a OSGi service(in sample 1). However, Service interface is implemented by single class. According to YAGNI design principle, Creating interface for only one class is unneeded. Instead of doing this, creating class which has methods is preferable(in sample 2). If I choose sample one, I will ignore some convensions including YAGNI and class naming(not impl suffix but specific name). If I choose sample 2, It won't suitable for OSGi environment. I am confused what I should do.
I'm currently developing a 3-Tier actix web REST API. It works very well, but I'm struggling conceptually on how to handle errors without copy pasting all my match arms and duplicating common errors between my services.
Right now, my application looks like that:
RepositoryA
-> always returns QueryResult (Result<T, Error> from diesel)
ServiceX
-> do_a() returns data or my ErrorEnumA (AlreadyExists,GenericDBError,HashError)
-> do_b() returns data or my ErrorEnumB (GenericDBError)
-> do_c() returns data or my ErrorEnumC (CourseFull,CourseNotExists,GenericDBError)
ControllerG
-> get_t() calls serviceX do_a and do_b and matches the errors to Result<HttpResponse, MyApiError>
MyApiError is a ResponseError, setting the http status and a json body with message and code.
With that architecture, I've got the following issues
Since everything has it's own enum, I can also not share a mapping from ErrorEnum to ApiError. Merging all service error into a big enum also is not possible, as the caller would never know which of them might be given back by the service he's currently calling.
That means my controller with only one method already looks like this:
#[post("/user")]
pub async fn register(
pool: web::Data<db::PgPool>,
register_user: web::Json<user::RegisterUserDto>,
) -> Result<HttpResponse, ApiError> {
let conn = db::get_conn(&pool.get_ref())?;
let result = web::block(move || {
service::registration::register_user(
&conn,
InsertableUser {
username: register_user.username.clone(),
password: register_user.password.clone(),
email: register_user.password.clone(),
birth_date: register_user.birth_date.clone(),
},
)
})
.await;
return match result {
Ok(u) => Ok(HttpResponse::Ok().json(u)),
Err(e) => match e {
BlockingError::Error(e2) => match e2 {
RegisterError::UsernameAlreadyExists(username) => Err(ApiError::new(
409,
format!("Username {} already exists", username),
1001,
None,
)),
RegisterError::GenericDatabaseError(_) => Err(ApiError::new(
500,
StatusCode::INTERNAL_SERVER_ERROR
.canonical_reason()
.unwrap_or("")
.to_string(),
5000,
None,
)),
RegisterError::HashError(_) => Err(ApiError::new(
500,
StatusCode::INTERNAL_SERVER_ERROR
.canonical_reason()
.unwrap_or("")
.to_string(),
5001,
None,
)),
},
BlockingError::Canceled => Err(ApiError::new(
500,
StatusCode::INTERNAL_SERVER_ERROR
.canonical_reason()
.unwrap_or("")
.to_string(),
5002,
None,
)),
},
};
}
Is there any established pattern to do that? Implementing the From for ApiError trait also does not help much. Should the service layer return HttpResponses in form of my ApiErrors directly, instead of using an own error enum? That would reduce the match arms in the controller. Then I could only call one service method per controller method though.
I think the only thing that could work is that all service methods return their errorEnum, but somehow they can share common errors. And there is a mapping from each error to an ApiError Response, which is called in the controller if the flow is finished at that point.
I'm trying to understand how to make and use a proxy design pattern. I have no idea what am i doing wrong. Any suggestions would be appreciated:
Load method should simulate downloading configuration from remote server... and it kinda does. The 2 seconds delay should be launched just once, and then it should go smoothly.
public interface ConfigLoader {
String load();
}
RealObject
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.RandomStringUtils;
import pl.sdacademy.prog.streams.MyExepction;
@Getter
@Setter
public class ConfigLoaderImplementation implements ConfigLoader {
private String configuration;
private String serverUrl;
public ConfigLoaderImplementation(final String serverUrl) {
this.serverUrl = serverUrl;
}
@Override
public String load() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new MyException("Sleeping canceled!", e);
}
System.out.println("Configuration from " + getServerUrl() + " downloaded successfully");
String generatedConfiguration = RandomStringUtils.randomAlphabetic(10);
setConfiguration(generatedConfiguration);
return generatedConfiguration;
}
}
Proxy
import lombok.Data;
@Data
public class ConfigLoaderProxy implements ConfigLoader {
private ConfigLoader proxy;
public ConfigLoaderProxy(String url) {
this.proxy = proxy;
}
@Override
public String load() {
if (proxy == null) {
proxy = new ConfigLoaderImplementation("www.blablA.com");
return proxy.load();
} else {
return proxy.load();
}
//todo
}
}
Test class, with main
public class ConfigLoaderDemo {
public static void main(String[] args) {
ConfigLoader proxy = new ConfigLoaderProxy("sdasd");
proxy.load();
proxy.load();
proxy.load();
}
}
Bán quần áo, phụ kiện có cần làm marketing? ❎Giữa hàng loạt shop thời trang mọc lên liên tục, làm sao để khách hàng biết đến bạn? ❎Tại sao khách hàng có thói quen lướt Facebook, Instagram mà bạn lại chưa đánh mạnh tên tuổi, sản phẩm của mình trên đấy? ❎Thời gian để bán hàng, kiểm hàng, xử lí đơn hàng,... bạn có còn thời gian để làm marketing đẩy mạnh thương hiệu?
===> Hãy để phòng marketing thuê ngoài STREETNET bao cân tất tần tật cho bạn nhờ các dịch vụ: ☑️Chụp hình chuyên nghiệp ☑️Content thu hút ☑️Chạy quảng cáo đúng đối tượng ☑️Đề xuất kế hoạch truyền thông, khuyến mãi hấp dẫn ☑️Quản trị và chăm sóc Fanpage chỉn chu ☑️Marketing trên Facebook, Instagram và cả website
Streetnet Media - Tư vấn và thực hiện marketing trọn gói 📞0935 616 639 ✉️info@streetnetmedia.com 📌240 Phan Đăng Lưu, Đà Nẵng https://streetnet.vn/
In the case of a 3 tiers application with:
The agent is sending events to the grpc server. It could be a single event but it could also be a couple of hundred ones in a single batch. There is no general pattern on how many events at which frequency.
What kind of caching could be set up to avoid having 1 call / 1 write into the database?
Because it is grpc, there is the possiblity of using streams. However, the stream needs to be kept opened with the server as events are occurring at random times.
There could also be client-side or/and server-side caching to allow bulk writes into the database.
What kind of software engineering pattern would you do in this scenario?
Suppose that I have a business logic layer, in which I have made something similar to a repository pattern. Each class in my repository extends the same generic class, in which i have basic CRUD operations.
I have run into a problem, where I need to write the same logic for the tables in my database, where I have a many-to-many relationship - which I probably have 5 places in my ORM.
Initially, I thought about putting this logic inside the generic class to enforce DRY - However, this may be a very bad idea, since my non-many-to-many tables will be able to access these specific methods as well.
Another approach, would be to include this logic within each of my repository classes, meaning that i then would have to repeat my code - naturally I don't like that.
Therefore, this is more of a design question. But I would really like to know, how you believe this could be solved in order to make my code as clean as possible.
I am learning classical design patterns and came across factory and abstract factory-like below
namespace factorydesign
{
interface IHomeAutomation
{
void Activate();
}
}
namespace factorydesign
{
class LightsConcreate : IHomeAutomation
{
public void Activate()
{
Console.WriteLine("Lights have been turned On");
}
}
}
namespace factorydesign
{
class AirConditionerConcreate : IHomeAutomation
{
public void Activate()
{
Console.WriteLine("Aircondition is Activated");
}
}
}
namespace factorydesign
{
class HomeAutomationFactory
{
public IHomeAutomation Selection(string sel)
{
switch(int.Parse(sel))
{
case 1:
return new LightsConcreate();
case 2:
return new AirConditionerConcreate();
default:
return new LightsConcreate();
}
}
}
}
namespace factorydesign
{
class Program
{
static void Main(string[] args)
{
HomeAutomationFactory HAF = new HomeAutomationFactory();
Console.WriteLine("Hello i am Sakura. I am your smart home Automation System");
Console.WriteLine("For Turning Lights Press 1");
Console.WriteLine("For Aircondition Press 2");
string selection =Console.ReadLine();
IHomeAutomation selObject = HAF.Selection(selection);
selObject.Activate();
}
}
}
I have the above home automation system where users can activate lights or air-condition.
Let's suppose tomorrow I need to scale this up. Let's say like add light brightness setting, control lights in one room, or increase temperature, sleep mode for air-condition and so on.
So how should I set up my application when I know there will be scalabilities in near future?
I am learning design patterns from the Head first design patterns book. The book has mostly toy examples, but sometimes they mention real world examples of usage of a design pattern. For example, the Decorator pattern is used in Java's Input Stream class to read from files, strings etc. Unfortunately, the book don't always mention real examples of where a design pattern is used. So, I was looking for a list or catalog which lists all design patterns and examples of its use in any open source project.
Do you know if such a catalog exists ? If not, then please add any examples that you know of so that a complete list can be built.
Decorator pattern usage - java.io.InputStream
Photo - link.
Observer pattern - ?
Strategy pattern - ?
etc...
Thanks!
PS - I prefer to NOT use the Gang of four/GOF book as an example because it does not use Java and you have to learn a lot about the application the authors use in their examples. I'd like to use isolated examples like the InputStream one.
Suppose i have to model credit card report and debit card report. Consider they both have same properties like transaction amount, date of transaction, place of transaction, transaction id and status of transaction.
How should i model this in Java ? Should i create Single class like Creditdebit class having properties as mentioned above and use it for creating credit report as well as debit report? or create separate classes as they are fundamentally different ? how should i handle this kind of scenarios? Help me with resources in dealing such cases or if there is any pattern to handle scenarios like this.
I have a base class that looks something like this
class Object {
public:
virtual void print() = 0;
virtual void set(std::string) = 0;
virtual void delete() = 0;
};
Instances of Object are meant to exhibit certain behavior, like being able to set some data, print the data set in it, and delete the resources taken by the node (please ignore the fact that this could be done with destructors for now). Calling any of the other two functions after calling delete()
causes an exception to be thrown. These functions are safe to invoke under concurrent workloads (with reads being trivially safe, while writes need to be serialized via a mutex, a write thread, or something similar)
Then I have an implementation of this interface that is exposed only as part of an ordered data structure - say a linked list. However, there is one behavior difference with the description of the base class above - when we call delete on a node, it deletes not only the node, but all nodes before it.
Is there a particular type of design pattern I can use to show the difference in behavior of the delete() function? I could for example, say in the comments that instances can spontaneously get deleted themselves, and that users need external synchronization (eg. from the linked-list implementation), but not sure if that's the best solution (maybe some sort of capability query is appropriate here?).
I have two reports that I am creating. I first map the data from a db query to a domain object. There are about 55 fields in one and 51 fields in the other report.
However 49 of the fields from the first report with 55 fields are also in the second report with 51 fields.
Would it be better to have them as separate classes and more decoupled or combine them into one generic "report" class/object?
I don't think creating a parent class with the common fields and have 2 classes extend from them is the best approach since it's a domain object so only getters and setters and then the subclass would have like only 2 fields, seems a bit much.
Would joining these two classes be considered a DTO? Is a DTO only when you create another object from the domain object that fits your presentation layer requirements i.e has only the required data.
after reading that Singletons are evil over and over again, i'm not sure how to implement a class that handles "crud" operations of a dataset, that contains some settings on a server.
The dataset does not really exists on the client side. The client only see its name and can initiate the server to load, save or delete its datasets.
To be indipendent on the server, the server instance will be "injected". The user can pass the name of the concerned Dataset.
class DataSet {
constructor(name, server) {
this.server = server;
this.name = name;
}
async load() {
this.server.sendLoadCommand(this.name);
}
async delete() {
this.server.sendDeeleteCommand(this.name);
}
// ...
}
In most cases only one method is needed at a time. Then the object is no longer required.
new Dataset("foo").delete();
Since theoretically the same object can be used every time, a global manager (singleton) could be used.
const window.dataSetManager = {
async load(name) {
this.server.sendLoadCommand(this.name);
}
async delete(name) {
this.server.sendDeeleteCommand(this.name);
}
// ...
}
window.itemManager.server = server;
Can anyone tell me the advantages of one or both ways?
Many thanks, Meisenmann
Route 1:
Route 2
Now need to build a Status table with Success and Faliure Status. If any message fail then STATUS = FAILED else STATUS = STARTED
Route 1:
.split(body().tokenizeXML("EmploymentUpdateRequest", "EmploymentUpdateRequests")) // Split and tokenize the requests, streaming individual requests to message queue
.unmarshal(new JaxbDataFormat(JAXBContext.newInstance(EmploymentUpdateRequest.class)))
.bean("someService", "updateEmployeeData")
.marshal(new JaxbDataFormat(JAXBContext.newInstance(EmploymentUpdateRequest.class)))
.inOnly(EMPLOYEES_QUEUE)
.choice()
.when(header("CamelSplitComplete"))
.log("Download xml file completed");
Route 2:
from(EMPLOYEES_QUEUE)
.unmarshal(new JaxbDataFormat(JAXBContext.newInstance(EmploymentUpdateRequest.class)))
.log("Extracting Data from Master")
.bean("employeeService", "extract")
.log("Verifying whether Data is correct or not")
.bean("employeeService", "verifyExchange")
.log("Persisting data to Master")
.bean("employeeService", "save");
Any suggestion to achieve this in Camel deployed in Cluster wildfly which picks messages randomly like 7000 one server picks 10000 1 picks?
I have a class with some calculation login in backend:
public class MyDomainClass{
private Double amount;
private Double total;
public Double getPercentage(){
/*business logic*/
}
}
My frontend is in angular 2+ and I want to show this information in 2 ways.
In a table with a list of them provided by the server:
And in a edition form, with the percentage calculation based on user input:
To make this calculation in the form I have to duplicate the logic in a frontend domain class too? I'm afraid to duplicate business logic and lost control of the code with more complex problems with this same idea (Some logic in backend for reports and list and the same logic in frontend forms).
How can I avoid that?
P.S: I use Jax-rs in the backend.
I'm having some issues with my game architecture and the way to handle coroutines. I am on a small tile game where the player has to click on some tiles. Those tiles contains different kind of ennemies, objects or are just empty. The feedback actions are differents depending on which entities are clicked. Basically, the player moves on an empty tile, attacks ennemies then get some loot, etc.
So it's turn based and the player has action points to use before giving the hand to the ennemies. Then they move, attack the player regarding their own behavior.
The problems I struggle with are the tweens and coroutines stuff. I would like to wait all the animations linked to an action before playing the next one.
What I have now is a 'master class' handling states and player inputs. Each states are based on the same interface with generic actions like: Init(), Play(), End().
But I'm still not sure of what I am doing or if I am just putting too much complexity. And I don't know how to simply handle using a weapon.
internal class PlayerTurnDungeonState : IDungeonState
{
DungeonApplication app;
public PlayerTurnDungeonState(DungeonApplication app)
{
this.app = app;
}
public void Init()
{
app.player.RestoreMana();
}
public void Play(Player player, Entity target)
{
if (player.isReady)
{
player.isReady = false;
IItem item = player.GetActiveItem();
if (target is Opponent)
{
if (player.CanUse(item) && player.CanTarget(item, target))
{
app.animationManager.AddAnimation(
player.UseItem(item, target) //returns UseItemCommand
);
}
}
else
{
(...)
}
}
}
public void PlayerCheck(Player player, Entity entity)
{
if (player.life.value == 0)
app.GameOver();
else if (player.mana.value == 0)
app.EndOfTurn();
}
public IDungeonState GetNextTurn()
{
return new OpponentTurnState(app);
}
public void End()
{
}
}
public class UseItemCommand : ICommand
{
private IItem item;
private Entity target;
private Entity caster;
public UseItemCommand(Entity caster, IItem item, Entity target)
{
this.item = item;
this.target = target;
this.caster = caster;
}
public IEnumerator Resolve()
{
yield return caster.ConsumeAP(item.apCost);
yield return item.Use(caster, target);
}
}
class Weapon : Item
{
(...)
public override IEnumerator Use(Entity caster, Entity target)
{
yield return base.Use(caster, target);
yield return target.Hit(this.power.value);
}
}
public abstract class Item : IItem
{
(...)
public virtual IEnumerator Use(Entity caster, Entity target)
{
this.durability.value--;
}
}
Example of a flow: During the PlayerTurnState, when I click on a tile occupied by a monster, it sends the input to the master class. If the player is ready to do some action, I call state.Play(player, monster) the player checks if the weapon can be used then hit the poor monster. I have to handle a cast animation, an attack animation, a hit animation then sometimes the monster death animation etc. and maybe with some objects I don't need any IEnumerator.. So I don't know how to handle properly all that stuff >_<' and in that case I don't know where and how add my PlayerCheck() from the PlayerTurnState.
My target is to have flexibles class to manage and decline many objects with differents stats or behavior. What could be the best way to manage that? What I am doing wrong there?
I've built a RESTful API that fetches employees from the database, Now I want to implement search functionality that filters employees by name and then fetches it. In the frontend, I've fetched employees and then based on user input I'm converting both user input and result from db to lowercase and then matching for similarity? Do you think this problem can be approached in a different way? any other strategies? thanks
I'm parsing a file and looking for a pattern of 3 or 4 digits followed by a hyphen followed by 3 or 4 digits (123 - 123, 123 - 1234, 1234 - 123, 1234 - 1234).
I'm using this Pattern: (\\d{3,4} - \\d{3,4})
I am able to find the various permutations but when I retrieve the group, it is missing the first digit. For example, if I find '1234 - 1234', then matcher.group(1)
returns '234 - 1234'
Imagine that I have 100 users list in the database and I have 100 or more console applications that are using those users to log in somewhere. I need to use a unique user per application, I must not use the same user more than one application. How can I solve this issue, what is the best practice or pattern for that? That means a record have to read only one application/service.
I'm creating sample application with Coordinate design pattern for leaning. Please help me to understand it in better way. Thanks and regards..
I study the strategy design pattern and from what I see, there is a very similar way to implement the "behaviors" of an object.
one way is the strategy design pattern. in this way the object 'has-a' strategy that represent the behavior.
the other way is to make this object 'implements' the behavior (interface).
for example, in a game, I have 'Enemy' object and one Enemy is flying and one is driving. so until now, I would think about: first 'Enemy' object implements Flyable and the second 'Enemy' implements Drivable. but another solution can be first Enemy 'has-a' FlyingStrategy and the second 'has-a' DrivingStrategy.
I'm trying to find the better solution in terms of good design.
Thanks.
I have two objects, I want to make singleton class and then call them like this Row.init([789]).render(). In the first case I try and it works:
var Row = (function (options) {
console.log(options);
this.data = [123];
this.render = function () {console.log(this.data);}
this.init = function (data) {
this.data = data;
return this;
}
return this;
})();
but in the second case:
class Row {
constructor() {
this.data = {};
}
static init(data) {
this.data = data;
return this;
}
fill() {
return this;
}
render() {
console.log(this.data);
}
}
It cannot call render method, I think it doesnt return this for me. How do I fix it? And in the first case, how do I pass options parameter?
I have a String like
String str = "305556710S or 100596269C OR CN111111111";
I just want to match the characters in this string that start with numbers or start with numbers and end with English letters, Then prefix the matched characters add with two "??" characters. I write a Patern like
Pattern pattern = Pattern.compile("^[0-9]{1,10}[A-Z]{0,1}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
String matchStr = matcher.group();
System.err.println(matchStr);
}
But it can only match the first character "305556710S". But If I modify the Pattern
Pattern pattern = Pattern.compile("[0-9]{1,10}[A-Z]{0,1}", Pattern.CASE_INSENSITIVE);
It will matches "305556710S","100596269C","111111111".But the prefix of "111111111" is English character "CN" which is not my goal. I only want match the "305556710S" and "100596269C" and add two "??" characters before the matched Characters.Can somebody help me ?
I have a Parent Class P. The parent class has class member variables. I have a Child class C1. C1 has a final member variable F1. Class C1 is being instantiated from several places.
I have to add a new blank final variable F2 I cannot add that to Class C1 since I do not know the value of F2 from where class C1 is instantiated. Also, I do not the value of the F1 from where I want to pass F2
Should I be creating a new child class for adding F2? How do I make a decision? If Yes: tomorrow, I have a requirement to add a new final variable F3 with similar constraints, should I be making another child class?
I am developing a desktop application which has very little input from the user. Most of the work of the application is to update views which show icons. The events are created in the model which communicates with an external device and reads a database.
WHich pattern is best suited for this type of application? I read quite a few posts and blogs about MVC and MVP, but most examples are talking about events coming from the user and not from the model!....
The application is developed in Python and I am thinking about using pyside 2 for the UI.
I want to match a pattern with this format /vX.X.X/ with X a number. for example : /v1.1.1/, /v.1.0.300/ etc..
I'm studying Design Patterns in Perl and using Phil Crow's comments for GoF. Is there a complete guide for Perl? I cannot find it.
I'm having trouble finding an optimal object oriented design for the following scenario:
Create an object oriented design for different types of smart devices. Different devices may have different inputs (typing and/or voice), outputs (sound and/or display), and power types (battery or plugged-in). Your design should be able to handle different input and respond to the correct output when asked about its battery status. (e.g.: "50% charged" or "plugged in").
Any ideas on what class hierarchy might be good for this scenario? Any design patterns that are applicable?
I'm trying to implement a Status Effect system on my game. I'll be calling Status Effect S.E to keep it short.
The primary focus on the game is on the magic system, and of course there shall be S.E's being applied to enemies you hit with certain spells. Common things like Slow, Stun, Snare, etc are present, but there shall be special S.E's with unique interactions(like Freezing the enemy when he's slowed bellow a threshold percent, triggering explosions when you hit an enemy with a fire spell and other crazy things you can imagine).
Since some S.E's types(like slow) require knowing all other S.E's of that type for the effect on the Actor movement to be applied correctly, the S.E's are applied to a IManager. Concrete examples on the usage of IManager: S.E's apply Decorators to a certaing actor component, and when one effect ends, things need to be restored and reapplied to avoid bugs. Increases and reductions to movement speed are applied like this: Flat changes first, Percent last, and percent are accumulative(10% slow now + 10% slow later result in 20% total slow if both S.E's are active)
In code, the interfaces looks like this:
public interface IReceiveStatusEffect
{
Dictionary<string, IStatusManager> StatusManagers { get; set; } //ID of the effect and the Manager for that Effect
void ReceiveEffect(IStatusEffect effect);
}
public interface IStatusEffect
{
IStatusManager Manager { get; set; }
GameObject Target { get; set; }
float Duration { get; set; }
string ID { get; } //The ID is Used on concrete implementations to get the SpellManager from IReceiveStatusEffect
void ApplyEffect();
void RemoveEffect();
}
public interface IStatusManager
{
List<IStatusEffect> AllEffects { get; set; }
void ProccessEffects(); // Called when an Effect is removed and some things needs to be recalculated. Sometimes call Apply again from the remaining AllEffects
}
An Actor that can receive an S.E need to have a IReceiveStatusEffect, so the flow is like this:
ConcreteStatusEffect status = new ConcreteStatusEffect(target, duration, IReceiveStatusEffect.StatusManagers);
// Constructor gets the correct manager from StatusManagers or create it if there's none
IReceiveStatusEffect.ReceiveEffect(status)
With everything (over)explained, here's the problem i'm facing: Since S.E's are quite diverse, some will require knowing concrete implementations of something(like concrete implementations of IStatusManager), like the Slow S.E example i gave earlier. I tried simply casting, and it worked, but pretty much everywhere i look everyone says that casting shall be avoided at all costs; That if you need to cast, there's probably a bad design there; That casting is an anti-pattern, etc
But I just have no idea on how i can get the information i need right now without casting. I thought and thought, but this flow seems to be the best(if not for the casting) for what i currently need, and can't think of another design pattern for the problem, so I'm trying to find a solution that does not use castings since it seems frawned upon.
Feature to compare the two documents of customer data maintained at respective service end VS the document maintained at Business/Customer end.
Output will provide reconciled document(amount difference between files) with flag for actions
Proposed Solution :
There will be a System which can take these two document Such that
Note : Input combination may vary as per business need Rule Engine can adapt both input with such combination
Is there a way of delegating in react native just like in swift/ios.. If we want to pass a information to a child class from parent class, we can do it by passing props. But what if we want to pass some information from the child class to parent class.
PS: No Redux or singleton approach.
I'm prototyping right now on a bigger project and need to make some design decisions..
My VS Solution consists (for now, might separate it further later) of 4 projects:
AzureTableStorage<T>
resides)For storage I'm using Azure storage table, and my problem is to find an elegant decoupled way of implementing this.
I'm using this example more or less: https://www.c-sharpcorner.com/article/single-page-application-in-blazor-with-azure-table-storage/ for CRUD operations to the tables.
But in order to use this I'm relying on inheriting TableEntity
, which is annoying. Also my WebUI is using Blazor, so it takes in a bunch of Azure Cosmos dll to the browser that is not needed if I choose to inherit TableEntity
.
So I can't decide if I just need to pursue decoupling my poco classes and get rid TableEntity
.. I saw something about using TableEntityAdapter
, but can't find any example using it?
Another approach might be to have Dto "duplicate" classes of my POCO classes, which then could inherit the TableEntity. But then I would need to maintain these classes. But might be needed since I don't think the methods in Azure Storage library can handle lists, enumeration etc. out of the box. But then again if I can make some generic adapter that takes care of more complex types, a Dto class could be redundant.
Looking for input and inspiration basically :)
Thanks
I'm implementing a template method design pattern in python, and have a question about whether a helper function in the abstract class' template method should be an instance or static function. Both would work, but I'm not sure on the pros and cons of both approaches.
I'm writing a framework to support testing images, where I can plugin different test methods depending on the type of image etc, hence I'm using a template method design pattern.
The abstract class template method to do the testing will need to support testing images in parallel, and will support doing this either using Multiprocessing (if running locally) or via AWS lambdas if running on AWS.
I want to encapsulate the details of the 'run_tests_locally' and the 'run_tests_lambda' into helper functions to avoid cluttering the main template method.
My question is whether it's best to make the above 'run_tests' functions as A) instance methods, or B) static methods in my abstract class definition. ...See below
Both would seem to work, but not sure which is best, and would love some guidance/thoughts
from abc import ABC, abstractmethod
import util.misc as misc
class TestFramework(ABC):
"""
Abstract class for executing tests
"""
@abstractmethod
def filter(self, objs):
"""Take list of objects, and return filtered list of those to test"""
pass
@abstractmethod
def do_test(self, obj):
"""Take a single object, test it, and return dict of results"""
pass
def execute_test(self, file_list):
"""Execute test"""
# library function
all_objs = misc.load_files(file_list)
# instance template function - shortlist objects
to_test_objs = self.filter(all_objs)
# now test objects
# how is it best to implment the 'run_tests' functions?
# A) instance methods?
# B) static methods?
# if running on aws, do tests across multiple lambda
# if local, use MP to run in parallel
if env = 'aws':
# as an instance method
test_results = self.run_tests_lambda(to_test_objs)
# as static:
test_results = run_tests_lambda_STATIC(to_test_objs, self.do_test)
else:
# instance form:
test_results = self.run_tests_local(to_test_objs)
# static form:
test_results = run_tests_local_STATIC(to_test_objs, self.do_test)
return test_results
# instance method implementation
def run_tests_local(self, to_test_objs):
all_results = {}
with ProcessPoolExecutor as e:
procs = [e.submit(self.do_test, obj) for obj in to_test_objs]
for proc in as_completed(procs):
all_results.update(proc.result())
return all_results
# static method implementation
@staticmethod
def run_tests_local_STATIC(to_test_objs, test_fn):
all_results = {}
with ProcessPoolExecutor as e:
procs = [e.submit(test_fn, obj) for obj in to_test_objs]
for proc in as_completed(procs):
all_results.update(proc.result())
return all_results
I have a UVC driver to get image from a UVC camera. UVC driver allows to connect with the device for one application at a time. I need to convert this into multiple application serving driver. driver is transferring image data in ASCII format. I am thinking of using sockets for implementation between client applications and the driver but I am struggled with designing a way to provide a client interface. I need to expose set of image events for application but I dont't have any idea on how to design this. any good documentation for designing client server applications using sockets (not just socket communication) will help.
I need to make a patter like this:
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
The problem is that i can't reverse the second part which is the same as the first part just reversed.
Here is my code:
for i in range(n // 2):
pattern = [('.|.' * (2 * i + 1)).center(m, '-')]
print('\n'.join(pattern))
print('WELCOME'.center(m, '-'))
for i in range(n // 2):
pattern = [('.|.' * (2 * i + 1)).center(m, '-')]
print('\n'.join(pattern[::-1]))
The patter[::-1] should be the reversed one.
It's not a repetitive question. Please read carefully.
I just got this new project and i happily started working on it but as this project is growing bigger & bigger due to regular Clients requirements, i'm afraid that i may run into performance issues.
I've 10 pages. View of each page is similar but with minor changes like different images,boxes,color for each page.I'm using MVVM pattern.So, the architecture i designed is as follows:
Now, here comes the problem. At starting, The CommonVM ViewModel was small but now as my project is growing , i am adding more and more Bindable properties in it.It already contains around 100 Properties and looks like it will grow more.
So,my question is,how can i handle this growing size of CommonVM ViewModel. How can i split it into multiple files or reduce it.
let N = 50
for i in 1...N
{
for j in 0..<(N-i) {
print(" ", terminator: "")
}
for j in 1...2 * i-1 {
print("*", terminator: "")
}
print("")
}
if (N > 1) {
for j in 2...N
{
var i = N - j + 1
for k in 0..<(N-i)
{
print(" ", terminator: "")
}
for k in 1...2*i-1 {
print("*", terminator: "")
}
print("")
}
}
import java.util.Scanner;
public class numPattern1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 1;
while (i <= n) {
int space = n - i + 1;
while (space <= n) {
System.out.print(" ");
space++;
}
int j = 1;
int p = i;
while (j <= i) {
System.out.print(p);
p++;
j++;
}
System.out.println();
i++;
}
}
}
output :
1
23
345
4567
but i want pattern in opposite direction:
1
23
345
4567
I've recently started working on a legacy frontend application (pre ES6, jQuery). There is no framework in place and no plans of implementing one in the near future. I am looking to modernize the codebase with ES6 features, including ES6 modules, however there is a sticky issue for me in that some of the potential modules are ones which will become licensed in the future. So basically, there will be a core app and some extra modules which can be bought separately.
All of this is in the future (the backend is not ready) but I would imagine the frontend will receive a list of available modules that the customer has paid for and these can be loaded along with the core app.
My question is more of a design pattern question with regards to the approach I should take. For example, in the current application and in what will be the core application, there is a global settings page. Some of the settings are for features which will only be part of a paid extra (i.e. licensed module). If the application is started with no extra modules, those settings should not be available, and vice-versa. I'm new to software architecture, but I would have thought that the core application should not need to know about extra module.
As regards to a solution, I was thinking about something like a registry of modules which would be populated based on what has been provided from the backend. (i.e., what the customer has paid for). I can then use this registry to add extra settings to the global settings page, but I'm kinda lost about whether this is a good approach. I'm basically wondering if there is some kind of common design pattern for this kind of thing?
I have an abstract class called IDataStream and it has one method. I create two implementations for this abstract class called IMUDataStream, GPSDataStream. In future there is a possibility that I may add another implementation of IDataStream abstract class. I have another class called DataVisualizer that visualizes all the data pulled by different DataStream classes.
In future if I add another DataStream implementation of the IDataStream abstract class, I should not be modifying the DataVisualizer class to visualize the data. Is there a way to create objects of all the derived classes of the IDataStream class, add it to a list and iterate through the list and use it to call the methods that will give me the data ?
Please note that I'm new to python and design patterns. Trying to learn. This may be a complete dumb question and total madness. I actually have a requirement for this. If this can be achieved through a design pattern I request the reader to point me to the material. Help much appreciated. Thanks !
#!/usr/bin/env python3
from abc import ABC, abstractmethod
class IDataStream(ABC):
def get_data(self):
pass
class IMUDataStream(IDataStream):
def __init__(self):
self.__text = "this is IMU data"
def get_data(self):
print(self.__text)
class GPSDataStream(IDataStream):
def __init__(self):
self.__text = "this is GPS data"
def get_data(self):
print(self.__text)
class DataVisualizer:
def __init__(self):
# somehow create objects of all derived classes of IDataStream here and call the get_data() function
# even if I add another derived class in the future. I should not be modifying the code here
*
**
***
******************
*******************
******************
***
**
*
I am trying to print this pattern in Java.
I want to write a script experiment.m
that will call a complicated function called encoder(...)
. encoder
will involve a lot of settings that experiment.m
is going to choose at runtime. At some point in experiment.m
, the settings which encoder
will use are created as variables (in this example there are two, in real life there can be dozens):
blocklength = [some derivation];
bitdepth = [some derivation];
I create a struct that stores these values under their names:
encoder_settings = struct();
encoder_settings.blocklength = blocklength;
encoder_settings.bitdepth = bitdepth;
And I write my encoder function like this:
function encoder_out = encoder(data, encoder_settings)
blocklength = encoder_settings.blocklength;
bitdepth = encoder_settings.bitdepth;
[...]
end
This works fine for code of moderate complexity, but after a while it becomes difficult to maintain the create-struct/load-struct blocks.
Alternatives I can think of don't seem great either:
encoder
is usually very complex and calling the variables directly from the struct in its body makes the code difficult to read.for s = fieldnames(my_struct)' eval([s{:},' = my_struct.', s{:}, ';']); end
I am trying to generate two sets of string images. 1st.
% % %
% % % % %
% %
%
2nd.
%
% %
% % %
% % % %
Note that the 2nd image is the same as the 1st image, just rotated counter-clockwise.
The number of lines and length of each line in the 1st image is based on a list, which can be of any length and consist of strictly positive numbers. In this example, our list is:
list = [3, 5, 2, 1]
I am having some trouble getting the 2nd image. For the first image, I have made use of the following function:
for e in list:
print(int(e) * '% '
Which seems to work. I am just not sure how to go about the 2nd image. I have some ideas around producing each row where I can find the highest element in list, find its index (in this example list[1]), and then incorporate " " on either side, depending on its distance to the beginning of the list and the end and going from there, but I am just not sure.
Any advice would be appreciated.
Thanks!
This question is highly related to this over question. I'm asking another question between I still am a bit confused on the topic.
I currently have a Django web application where users can have a list of their hobbies and can increment a counter each time they do one of their hobbies. My issue is, I want to extend this functionality outside of a front-end experience. In other words, I want users to be able to increment their hobbies using a POST
request, say, from the terminal or from their own script or something.
Do I have to create an API for my webapp to add this functionality?
Another way to put is, do I have to handle requests coming from the front-end differently than requests coming from somewhere else? Would front-end requests go to the URL www.hostname.com/hobbies/1
and other requests go to the URL www.hostname.com/api/hobbies/1
?
If I do route the POST
requests to the same URL as the requests coming from the front end (i.e. www.hostname.com/hobbies/1
), then how come google has external APIs for Google Maps? It seems like if other web applications are calling Google Maps functionality then Google has separated those instances from their front end.
I am working on a spring boot project where i need to call different provider api based on the vendor that the client is interested.I have the details of the API stored in the database.
The client request this service to get the data by passing a standard request plus the vendor name.The service internally will call vendor api by converting the standard request to the request model required by the vendor API.Each vendor API has different one is Rest based API(HTTP) and other is SOAP(SOAP) based api and the authentication mechanism also differs.I was wondering any pattern /open source code i can refer to optimise the solution.
Currently, i have vendor specific implementations and client classes to perform this functionality. I was wondering any other patterns/open source code present to solve the same use case.
Why every where I look the inner builder class is public static? Shouldn't it be private static? Maybe I don't see something but I would say it would be better. Could anyone explain it to me?
@Getter @AllArgsConstructor @ToString
public class CarDto {
private final String make;
private final int seatCount;
private final String type;
private final CarDto carDto;
public static Builder builder(){
return new Builder();
}
private static class Builder{
private String make;
private int seatCount;
private String type;
private CarDto carDto;
public Builder make(String make){
this.make = make;
return this;
}
public Builder seatCount(int seatCount){
this.seatCount = seatCount;
return this;
}
public Builder type(String type){
this.type = type;
return this;
}
public Builder carDto(CarDto carDto){
this.carDto = carDto;
return this;
}
public CarDto create(){
return new CarDto(make, seatCount,type,carDto);
}
}
}
I'm working on a solution where an angular application is consumed inside an iframe of another angular application. The child app need some parameters to show the correct information into the app parent. I read a lot of solution around the web and a good solution is to apply the design pattern publisher/subscriber.
A lot of example are between component inside the same application and I'm wondering if the same solution with rxjs objects is the right way (as shown here).
My doubt is: how I subscribe the child application to the parent (an external publisher)?
I was thinking on a REST API exposed by the parent for registration and unregistration of subscriber, but I'm not sure.
Any experience with this situation? Thanks in advance
Trying to design a hierarchy of classes which allow composition (set of elements) I come to a blocker since I don't really know which pattern to apply here, but I know there's one.
The context is the following.
I would like to define a kind of Structure
which contain several Element
objects. However, within this Element
objects I can have more Element
objects since they can be nested n
degrees inside.
I can think of Decorator since it's like "take an element, and decorate it with whatever more you want", but not sure that this is what I really need since, check the diagram below.
What if ConcreteElement
contains yet another Element
or List<Element>
? Is there a sub-pattern for this or can I just infer those within the class as attributes and handle the logic within process()
?
Would like to set the elements as structure and then that each element could call himself or any of its child Element objects, same level in the hierarchy, to complete itself.
I'm confused about the patterns: ViewModelLocator
, ServiceLocator
, Dependency Injection
.
The latest conclusion are as follows:
ViewModelLocator
. The place to connect View
and ViewModel
.
public ViewModelLocator()
{
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<SettingViewModel>();
}
public MainViewModel MainViewModel => SimpleIoc.Default.GetInstance<MainViewModel>();
public SettingViewModel SettingViewModel => SimpleIoc.Default.GetInstance<SettingViewModel>();
// View
private MainViewModel ViewModel => ViewModelLocator.Current.MainViewModel;
Dependency Injection
. A set of principles for weak connections. Often through the constructor.
private readonly INavigationService _navigation;
public ShellViewModel(INavigationService navigation)
{
_navigation = navigation;
}
ServiceLocator
. What is it? The same as ViewModelLocator
, but considered by many to be an anti-pattern? It turns out ViewModelLocator
is also bad. But how then to connected View
and ViewModel
? ServiceLocator
only needs to store Services? As you understand, all the confusion is from ServiceLocator
.
Could you explain the differences and similarities between these elements? To finally uniquely identify and use them correctly. Thank you for any help.
General question: How to avoid if-else ugly code when you have to deal with multiple checks based on some string type?
Example: I have an object "Task" in TODO app, which can be of different types, e.g. simple checkbox, textarea, date, a combination of fields etc. For each type of a "Task", there is different logic on how to change the object before saving it.
How to leverage typescript and organize the code without if-else statements.
I'm working on breaking up a large, monolithic class into several subclasses, but it's too much to do all at once so I'm looking to split them out one by one over several releases as time permits. It's an auth class that authorizes some channel, so currently it looks like this:
$auth = new Auth($user, $data);
$output = $auth->authChannel($channelName);
Inside Auth, it basically looks like this:
public function __construct($user, $data)
{
$this->user = $user;
$this->data = $data;
}
public function authChannel($channel)
{
$this->setUserData();
if (isset(self::CHANNEL_AUTH_FUNCTIONS[$channel])) {
$authFunction = self::CHANNEL_AUTH_FUNCTIONS[$channel];
return $this->$authFunction();
} else {
// invalid channel
}
}
So self::CHANNEL_AUTH_FUNCTIONS
is basically ['channelA' => 'authChannelA', 'channelB' => 'authChannelB']
, etc., and all those functions are in this one class.
Now what I want to do, one at a time, is if $legacyChannel => callLegacyFunction() / else $newChannel => instantiate its own class and call auth()
.
So I put Auth.php
into its own namespace and have the new Channel.php
class in that same namespace. And Channel extends Auth
.
Currently I have this:
public function authChannel($channel)
{
$this->setUserData();
if (isset(self::CHANNEL_AUTH_LEGACY_FUNCTIONS[$channel])) {
$authFunction = self::CHANNEL_AUTH_LEGACY_FUNCTIONS[$channel];
if ($authFunction) {
return $this->$authFunction();
} else {
$authClassName = __NAMESPACE__ . '\\' . ucwords($channel);
$authClass = new $authClassName($user, $data);
return $authClass->auth();
}
} else {
// invalid channel
}
}
Is there a better way to do this? Currently it seems a bit wasteful since two different objects are created and the setUserData()
function for example would need to be called again I believe. I'm also wondering if there's a better way to get the dynamic class name other than through __NAMESPACE__ . / . $className
.
Any help would be appreciated!
Given the following classes with the Lombok annotations @Data
and @SuperBuilder
@Data
@SuperBuilder
public abstract class Parent {
protected final String userId;
protected final Instant requestingTime;
}
@Data
@SuperBuilder
public class Child extends Parent {
private final Instant beginningDate;
private final Instant endingDate;
private final Collection<String> fields;
}
I am getting the following error appearing over the @Data
annotation in the Child
class:
Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor.
Is there a way to configure a non-default constructor on the Child
class's @Data
annotation in order to have all final
fields on both the Child
and Parent
classes initialized?
I have tried a few different combinations of the @Data
, @Getter
, @Setter
annotations with the @SuperBuilder
annotation on both the child and parent classes, but haven't found a working solution yet. I am using Lombok 1.18.10.
For reference, this question is related
I have set of entities(templates)
I need to clone full this set and create same set with new Ids.
I have 3 methods like this(Entity One is User):
private Map<String, String> createUsers() {
Map<String, String> userIds = new HashMap<>();
Iterator<User> users = userService.findAllUsers();
while (users.hasNext()) {
User user = users.next();
String oldId = user.getId();
user.setId(generateNewId());
user.setName(generateNewName());
userService.saveUser(user);
userIds.put(oldId, user.getId());
}
return userIds;
}
And two similar methods(Entity two is Person and Entity Three is Book). In each method, I create new entity and store old and new IDS. After that, I clone Orders and relink old id and new id. I do it like this:
if (userIds.containsKey(order.getUserId())) {
order.setUserId(userIds.get(order.getUserId()));
}
if (personIds.containsKey(order.getPersonId())) {
order.setPersonId(personIds.get(order.getPersonId()));
}
This structure is ugly and I want to refactor it. But I have not ideas.
enter image description herehow to print this pattern using while loop : user-input : 5
E DE CDE BCDE ABCDE
I have got a mapper class which does a complex mapping of one pojo to another. I made the mapper class a bean and wired it to the service class. I could have made the mapper class a static class as well but I preferred a bean because I felt it better in a testability point of view, I can test the service and mappers independently by mocking the mappers. Indeed it’s also possible to mock the static classes but I will have to use powermock or something similar. Another reason to choose a bean is that for certain mappers I had to use interfaces so that I can choose the mapper implementation based on certain data conditions.
This implementation as a bean has triggered a controversy in my team with suggestions to implement it as static class or to create new mapper objects every time. And we are trying to figure out what is the best solution. Are there any industry standards being followed. Are there any trade offs with the beans approach? Can it have any impact on the performance of my application? imagine that I have got a hundred such mappers. Below is a simple Skelton of how my service and mappers looks like.
@Service
class CustomerService { @Autowired CustomerMapper customerMapper ...}
@Component
class CustomerMapper { @Autowired CustomerContactMapper ..
}
interface CustomerContactMapper {}
@Component
class InternalCustomerContactMapper implements CustomerContactMapper {}
@Component
class ExternalCuatomerContactMapper implements CustomerContactMapper {}
I created state within App.js for a single page application (kanban board)
Within the state i have three key values with arrays and one other key value:
this.state = {
currentItem: { text: '' },
toDoListItems: [
{ text: 'hello world' }
],
inProgressListItems: [],
doneListItems: []
}
Currently my implementation of use cases like delete a task from any board, is implemented by passing the name of the list item.
ie. {() => this.deleteItem(item, "toDoListItems")}
How should i make my code more extensible? I was thinking first, I should place all the lists within an object within state. But is it good/bad practice to manually iterate and which array contains the element that I'm looking for? It feels like if i were to do that, I'm making redundant checks.
I am new to JS design patterns and have not used much of require
or import
. I have a single module which contains multiple functions and private variables, which is packaged into a module. Currently everything is in one file but splitting it into multiple files would be good practice and provide better clarity. The simplified view of the module's pattern looks something like this:
let Module = () => {
//some private variables
let private1,
private2;
//some public functions
function addDatatoPrivate1 (data) {
private1 = processData(data);
}
function addDatatoPrivate2 (data) {
private2 = processData(data);
}
//private function processData
function processData(data) {
return data.trim();
}
return {
addDatatoPrivate1: addDatatoPrivate1,
addDatatoPrivate2: addDatatoPrivate2,
}
}
I would like to split up the functions into multiple files i.e. separate file for addDatatoPrivate1
, addDatatoPrivate2
and processData
. In addition I would like to have the variables private1
and private2
be available for other methods in the Module privately. How do I go about splitting the code into multiple files and then how to use import
to get the different components of the module to package into one.
The eventual aim is to have something which a user can load into their own project and use something like d3js or jQuery. For example, with the code as above anyone can simply assign the module to a variable and use it like so:
let moduleInstance = Module();
moduleInstance.addDatatoPrivate1(' some data here ');
moduleInstance.addDatatoPrivate2(' some data here2 ');
I have two classes ExceptionLog
and DebugLog
public class ExceptionLog {
public static String StackTrace {get; set;}
public static String ClassName {get; set;}
public static String MethodName {get; set;}
public static String LogType {get;set;}
public static Exception ex {get;set;}
public Static void Debug(Exception ex)
{
logType = 'EXCEPTION';
ex = ex;
log();
}
public Static void log()
{
try
{
extractException();
writeToObject();
}
catch(Exception e)
{
//new ExceptionLog().Module('LogException').log(e);
}
}
public static void extractException()
{
// Logic here
}
public static void writeToObject()
{
// data save to object logic here
}
}
and
public class DebugLog {
public static String LogType {get;set;}
public static String DebugMessage {get;set;}
public Static void Debug(String message)
{
Debug(null, message);
}
public Static void Debug(LoggingLevel level, String message)
{
if(level != null )
{
LogType = String.valueOf(level);
}
DebugMessage = message;
log();
}
public Static void log()
{
// Log logic here
}
}
What I want to achieve is, write a controller class that will make decision of which debug
method needs to be called
public class Log {
public void Debug(String message)
{
DebugLog.Debug(message);
}
public void Debug(loggingLevel loggingLevel, String message)
{
DebugLog.Debug(loggingLevel, message);
}
public void Debug(Exception ex)
{
ExceptionLog.Debug(ex);
}
}
That is, if I pass Exception in the debug method, it will call the ExceptionLog.Debug(ex)
else it will call the debug method from DebugLog
class.
I know the the object oriented approach is not good here. How can I design the classes more elegantly or any design pattern fit here?
Within the context of enterprise integration patterns (EIP) there is the concept of a Normalizer -- which is composed of a queue, a content based message router, and a message translator to translate the different data formats to a uniform one.
I have always kept one queue for each kind of data. So when is this pattern necessary? It seems better to have a separate queue for each data format and route them directly to the appropriate translator -- and not have to rely upon (probably brittle) message identification.
Am I thinking about this wrong?
I have start a new position at Cadence design system Indago team as GUI developer using java swing, as you know when design patterns used for such big tools, i want to ask what design patterns should i know to start understand such complex code and architecture.
We are developing an Asp.net core application with a video streaming feature. The project contains an action on a controller that returns video stream. For an upcoming demo we need to mock a video stream using a single video file played in a loop for a demo. Business requirements expect the stream to appear the same on all clients, e.g. if the controller just loads the video file from the beginning when the web request starts each client will be viewing the video at different time points and it would not be synced like a live stream.
What is the best design/architecture to sync all of the clients video feeds based on a single video file stored on the webserver?
I want to implement an Abstract Factory pattern. Here is a factory:
export abstract class MyFactory {
abstract getAdapter(): DataAdapter;
}
Lets say we have 2 components AComp
and BComp
which belong to the same module AModule
. Both of them have the factory dependency:
constructor(
...
private factory: MyFactory
) {}
I wan to hide concrete factory creation logic. So the solution I came up with is to put the creation logic into AModule
:
@NgModule({
declarations: [AComp, BComp],
providers: [
{
provide: MyFactory,
deps: [MY_FACTORY_TOKEN],
useFactory: (token: string) => {
// return concrete factory depending on the token
}
}
]
})
export class AModule { }
And each component has its own token provider:
@Component({
...
providers: [ {provide: MY_FACTORY_TOKEN, useValue: 'string val' } ]
})
But it says No provider for InjectionToken myfactorytoken!
. Apparently I can't get the component provider on the module level.
Basically, my question is how to return concrete factory depending on current component? E.g. if it is AComp
then return AConcreteFactory
, if it is BComp
then return BConcreteFactory
.